雖然能夠用event攔截事件,可是有的時候咱們的應用中用到了不少的組件,或者咱們本身實現了一個組件繼承了不少其餘的組件,咱們要想經過event攔截事件,就變得很困難了,必須重寫全部的event()函數,異常的麻煩.ide
可是QT5給咱們提供了事件過濾器,該事件過濾器被安裝後起做用於事件發生以後事件分配以前(event()).函數
(public: vritual) bool Object::eventFilter(QObject* watched, QEvent* event);
該函數接受一個QObject* 的參數和一個QEvent* 參數,且該函數返回一個bool類型,若是咱們攔截掉了該event,那麼返回true.this
若是咱們想要事件繼續傳播,那麼返回false.spa
其中第一個參數QObject*類型的:是咱們安裝了事件過濾器的對象,第二個就是事件咯.code
全部組件都是QObject的子類記住!!!!!!!!!!!!對象
看代碼吧:繼承
#include <QWidget> #include <QObject> #include <QEvent> #include <QMouseEvent> #include <QDebug>
class Lable : public QWidget { public: inline Lable() { this->installEventFilter(this);//注意這裏給本身安裝事件過濾器. }
~Lable ()=default;
virtual bool eventFilter(QObject* watched, QEvent* event)override //事件過濾器. { if(watched == this){ if(event->type() == QEvent::MouseButtonPress){ qDebug()<<"eventFilter"; } }
return false; }
protected: virtual void mousePressEvent(QMouseEvent* mouseEvent)override { qDebug()<<"mousePressEvent"; //處理了事件. //由於mouseEvent默認是accept的. }
virtual bool event(QEvent* event)override //這裏也沒有處理該事件. { if(event->type() == QEvent::MouseButtonPress){ qDebug()<<"event"; }
return this->QWidget::event(event);//由父類的同名函數再次進行事件分配. }
};
class EventFilter : public QObject { public: EventFilter(QObject* watched, QObject* parent = nullptr):QObject(parent),watched_(watched){}
virtual bool eventFilter(QObject* w, QEvent* event)override //發生的全部事件首先通過該事件過濾器. { if(w = this->watched_){ if(event->type() == QEvent::MouseButtonPress){ qDebug()<<"Application EventFilter"; } }
return false; //返回fasle標明並無處理該事件.而後該事件傳遞給了Lable中的eventFilter. }
private: QObject* watched_; };
#include "mainwindow.h" #include <QApplication> #include <memory>
int main(int argc, char *argv[]) { QApplication a(argc, argv); Lable label; std::shared_ptr<EventFilter> event(new EventFilter(&label, &label)); a.installEventFilter(event.get()); label.show();
return a.exec(); }
上面的例子輸出是:事件
Application EventFilter
eventFilter
event
mousePressEventget
咱們再來了解一下安裝事件過濾器的函數:it
(public: virtual) bool QObject::installEventFilter(QObject* eventFilter);
其中eventFilter就是咱們想要安裝的時間過濾器.
installEventFilter()是QObject的函數,而QApplication和QCoreApplication都是QObject的子類,所以咱們就能夠給本身的應用程序安裝全局的事件過濾器.該應用程序級別的事件過濾器被安裝之後,全部其餘組件的事件過濾器發揮做用都在它的後面.