installEventFilter、eventFilter函数理解
生活随笔
收集整理的這篇文章主要介紹了
installEventFilter、eventFilter函数理解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
installEventFilter函數(shù)如下:
void QObject::installEventFilter(QObject *filterObj)
Qt助手的解釋如下:
在對象上安裝一個事件過濾器filterObj。如下:
monitoredObj->installEventFilter(filterObj);其中monitoredObj、filterObj都是QObject的子類。上面代碼意思是:在monitoredObj對象上安裝一個事件過濾器filterObj。該函數(shù)一般和如下函數(shù)配合使用:
[virtual] bool QObject::eventFilter(QObject *watched, QEvent *event)注意:該函數(shù)是虛函數(shù),也就是說派生自QObject的子類可以重寫該函數(shù)。
? ? ?上面monitoredObj對象安裝一個filterObj過濾器后,則可以在filterObj對象所在類的eventFilter函數(shù)中攔截發(fā)送到monitoredObj對象的事件。如下為KeyPressEater類:
class KeyPressEater : public QObject{Q_OBJECT...protected:bool eventFilter(QObject *obj, QEvent *event) override;};bool KeyPressEater::eventFilter(QObject *obj, QEvent *event){if (event->type() == QEvent::KeyPress) {QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);qDebug("Ate key press %d", keyEvent->key());return true;} else {// standard event processingreturn QObject::eventFilter(obj, event);}}現(xiàn)在我們在按鈕或QListView兩個窗體部件上安裝過濾器,如下:
KeyPressEater *keyPressEater = new KeyPressEater(this);QPushButton *pushButton = new QPushButton(this);QListView *listView = new QListView(this);pushButton->installEventFilter(keyPressEater);listView->installEventFilter(keyPressEater);此時(shí)如果在按鈕或QListView獲取到鍵盤焦點(diǎn)時(shí)按下Esc鍵,按鍵事件被?KeyPressEater類的eventFilter函數(shù)攔截,從而彈出:
Ate key press 1048576
其中1048576為Esc鍵的虛擬鍵碼。Qt的QShortcut類就是采取這種技術(shù)實(shí)現(xiàn)的。
注意:
- 事件過濾器對象filterObj能阻止(攔截)或放行發(fā)向?qū)ο髆onitoredObj的事件。
- 事件過濾器對象filterObj通過其類的eventFilter函數(shù)來接收事件。
- 如果過濾器對象filterObj所在類的eventFilter函數(shù)返回true,則該事件被攔截,也就是原本發(fā)向monitoredObj對象的事件不再發(fā)向monitoredObj對象;如果過濾器對象filterObj所在類的eventFilter函數(shù)返回false,則不攔截該事件,事件依然發(fā)向monitoredObj對象。
- 如果同一個對象上安裝多個過濾器,則最后一個過濾器首先被激活調(diào)用。
- 如果在eventFilter函數(shù)中刪除了接收事件的對象,請確保eventFilter函數(shù)返回true,否則Qt將會發(fā)送事件到刪除的接收對象上,這將導(dǎo)致程序崩潰。
- monitoredObj對象和filterObj對象必須位于同一個線程中。如果filterObj對象在不同的線程,調(diào)用installEventFilter函數(shù)則Qt什么都不會做。
- 如果調(diào)用installEventFilter函數(shù)后,monitoredObj對象和filterObj對象被移到不同的線程中去了,則eventFilter函數(shù)不會被調(diào)用,直到monitoredObj對象和filterObj對象回到同一線程時(shí)才會被調(diào)用。
- 過濾器對象filterObj所在類的eventFilter函數(shù)的第一個參數(shù)是被攔截對象monitoredObj,即installEventFilter函數(shù)的調(diào)用者。以上面的?KeyPressEater例子來說,?KeyPressEater類的eventFilter函數(shù)的第一個參數(shù)是pushButton或listView
? ? ?
總結(jié)
以上是生活随笔為你收集整理的installEventFilter、eventFilter函数理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: affine工程难点、亮点汇总
- 下一篇: 董明珠谈选择大城市还是家乡:不要强求一种