标签:exp ntp bubuko type 技术 slots 栈堆 自定义事件 注册
Qt发送事件分为两种
-阻塞型事件发送
bool QApplication::sendEvent ( QObject * receiver, QEvent * event ) ; // receiver:接收对象, event :要发送的event类型(比如:鼠标双击) //当有事件发送,将会调用receiver对象里的event()成员函数进行事件处理
-非阻塞型事件发送
void QApplication::postEvent ( QObject * receiver, QEvent * event );
示例-通过sendEvent()发送预定义的键盘Delete按键事件
Wiget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QtGui> class Widget : public QWidget { Q_OBJECT private : QTextEdit edit; QPushButton bt; private slots: void onPushButton(); public: explicit Widget(); }; #endif // WIDGET_H
Widget.c
#include "widget.h" Widget::Widget() : edit(this),bt("Delete",this) { edit.setGeometry(0,0,300,200); bt.setGeometry(310,20,48,32); connect(&bt, SIGNAL(clicked()), this, SLOT(onPushButton())); } void Widget::onPushButton() { int key = Qt::Key_Delete ; QKeyEvent EventPress(QEvent::KeyPress,key,Qt::NoModifier); QApplication::sendEvent(&edit,&EventPress); //发送键盘按下事件 QKeyEvent EventRelease(QEvent::KeyRelease,key,Qt::NoModifier); QApplication::sendEvent(&edit,&EventRelease); //发送键盘松开事件 }
效果
自定义事件对象
class StringEvent : public QEvent { public: static const Type = static_cast<Type>(QEvent::User+0x10); explicit QStringEvent(); //... ... } QStringEvent::QStringEvent() : QEvent(TYPE) //注册TYPE值 { //... ... }
常用两种方法来处理
1.通过事件过滤器处理
2.重写目标对象的event()函数
示例-通过单击鼠标按钮发送自定义事件QStringEvent
QStringEvent文件:
class QStringEvent : public QEvent { private: QString mstr; public: const static Type TYPE = static_cast<Type>(QEvent::User+0x10); explicit QStringEvent(QString s); QString str(); }; QStringEvent::QStringEvent(QString s) : QEvent(TYPE) { mstr = s; } QString QStringEvent::str() { return mstr; }
widget文件:
class Widget : public QWidget { private : QLabel label; bool event( QEvent * e); bool eventFilter(QObject *obj, QEvent *event); public: explicit Widget(); };
Widget::Widget() : label(this) { label.installEventFilter(this); } bool Widget::event( QEvent * e) { if(e->type() == QEvent::MouseButtonPress) { QMouseEvent *me = dynamic_cast<QMouseEvent* >(e);if(me->button() == Qt::LeftButton) { QStringEvent event( QString("X坐标: %1 Y坐标: %2").arg(me->x()).arg(me->y()) ); QApplication::sendEvent(&label,&event); //发送自定义事件 } } return QWidget::event(e); } bool Widget::eventFilter(QObject *obj, QEvent *event) { QLabel *t = dynamic_cast<QLabel* >(obj); if(t && event->type()== QStringEvent::TYPE ) { QStringEvent *str = dynamic_cast<QStringEvent* >(event); t->setText(str->str()); t->adjustSize(); return true; } return QWidget::eventFilter(obj,event); }
效果:
19.QT-事件发送函数sendEvent()、postEvent()
标签:exp ntp bubuko type 技术 slots 栈堆 自定义事件 注册
原文地址:https://www.cnblogs.com/lifexy/p/9042862.html