1 新建一个项目:06Event
新建cpp文件
2 QT消息过滤器
EventFilter.pro |
HEADERS += \ MyWidget.h \ MyApplication.h
SOURCES += \ MyWidget.cpp \ MyApplication.cpp
QT += widgets gui |
MyWidget.h |
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> #include <QPushButton> class MyWidget : public QWidget { Q_OBJECT public: explicit MyWidget(QWidget *parent = 0); QPushButton* _button; bool eventFilter(QObject *, QEvent *); bool event(QEvent *); signals: public slots: }; #endif // MYWIDGET_H |
MyWidget.cpp |
#include "MyWidget.h" #include <QPushButton> #include <QEvent> #include "MyApplication.h" #include <QDebug> #include <QApplication> MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { QPushButton* button; button = new QPushButton("This button", this); connect(button, SIGNAL(clicked()), this, SLOT(close())); _button = button; /*button给自己安装了一个消息过滤器,那么经过button的消息, * 都先要调用它的过滤器的eventFilter函数*/ button->installEventFilter(this); } bool MyWidget::eventFilter(QObject *o, QEvent *e) { #if 0 if(0 == (QObject*)_button &&( e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseButtonPress)) { return true; } #endif return QWidget::eventFilter(o,e); } bool MyWidget::event(QEvent *e) { if(e->type() == QEvent::User) { qDebug() << "User event is comming"; } return QWidget::event(e); } int main(int argc,char *argv[]) { MyApplication app(argc,argv); MyWidget w; w.show(); //发送一个Event给MyWidget qDebug() << "begin send"; app.postEvent(&w,new QEvent(QEvent::User)); qDebug() << "end send"; return app.exec(); } |
MyApplication.h |
#ifndef MYAPPLICATION_H #define MYAPPLICATION_H #include <QApplication> class MyApplication : public QApplication { Q_OBJECT public: MyApplication(int argc,char *argv[]):QApplication(argc,argv) {} bool notify(QObject *,QEvent *); signals: public slots: }; #endif // MYAPPLICATION_H |
MyApplication.cpp |
#include "MyApplication.h" #include <QEvent> #include <QDebug> bool MyApplication::notify(QObject *o, QEvent *e) { if(this->topLevelWidgets().count()>0) { QWidget* mainWnd = this->topLevelWidgets().at(0); if(o==(QObject*)mainWnd && e->type() == QEvent::MouseButtonPress) { // do ... qDebug() << "mainwnd is clicked"; } } return QApplication::notify(o, e); } |
运行结果: |