Qt处理事件的第五种方式:"继承QApplication并重新实现notify()函数"。Qt调用QApplication来发送一个事件,重新实现notify()函数是在事件过滤器得到所有事件之前获得它们的唯一方法。事件过滤器使用更为便利。因为可以同时有多个事件过滤器。而notify()函数只有一个。
重新实现的QApplication类MyApplication的头文件myapplication.h如下:
#ifndef MYAPPLICATION_H #define MYAPPLICATION_H #include <QApplication> #include <QEvent> class MyApplication : public QApplication { public: MyApplication(int & argc, char ** argv); public: bool notify(QObject *receiver, QEvent *e); }; #endif
myapplication.cpp文件如下:
#include "myapplication.h" #include <QMouseEvent> MyApplication::MyApplication(int & argc, char ** argv) : QApplication(argc, argv) { } bool MyApplication::notify(QObject *receiver, QEvent *e) { //屏蔽MouseButtonPress、MouseButtonRelease和MouseMove事件 if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove) { return true; } return QApplication::notify(receiver, e); }
mainwindow.h文件如下:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui/QMainWindow> #include <QPushButton> #include <QMouseEvent> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); protected: bool eventFilter(QObject *obj, QEvent *e); private: QPushButton *button; }; #endif
mainwindow.cpp文件如下:
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { button = new QPushButton; this->setCentralWidget(button); } MainWindow::~MainWindow() { } bool MainWindow::eventFilter(QObject *obj, QEvent *e) { if (obj == button) //响应button的MouseButtonPress和MouseButtonRelease事件 { if (e->type() == QEvent::MouseButtonPress) { QMouseEvent *event = static_cast<QMouseEvent*> (e); button->setText(QString("Press: %1, %2").arg(QString::number(event->x()), QString::number(event->y()))); return true; } else if (e->type() == QEvent::MouseButtonRelease) { QMouseEvent *event = static_cast<QMouseEvent*> (e); button->setText(QString("Release: %1, %2").arg(QString::number(event->x()), QString::number(event->y()))); return true; } else { return false; } } return QMainWindow::eventFilter(obj, e); }
main.cpp文件如下:
#include <QtGui/QApplication> #include <QtCore/QTextCodec> #include "mainwindow.h" #include "myapplication.h" int main(int argc, char *argv[]) { MyApplication a(argc, argv); QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030")); MainWindow mainwindow; a.installEventFilter(&mainwindow); //为QApplication注册过滤器 mainwindow.setWindowTitle(QObject::tr("继承QApplication并重新实现notify()函数")); mainwindow.resize(400, 200); mainwindow.show(); return a.exec(); }
运行程序,可以发现button不管是点击、释放还是拖动鼠标,都不会显示任何文本。因为我们已经子类化QApplication,事件在到达QApplication的事件过滤器之前,会先到达QApplication的notify()函数,我们已经在子类化的MyApplication中屏蔽了MouseButtonPress、MouseButtonRelease事件。所以为MyApplication对象注册的事件过滤器不起作用。程序运行界面为:
Qt事件系列(完)!