事件過濾器
/* *事件過濾器不是類,僅僅是QObject類的兩個函數:installEventFilter() 和 eventFilter() 。 *下面講個例子: * 監視過濾 textEdit的鼠標滾輪事件;監視過濾 spinBox的 空格按鍵事件。 *2018.4.2 張洪銘 */ //widget.h public: bool eventFilter(QObject *watched, QEvent *event);
//widget.cpp #include <QWheelEvent> #include <QKeyEvent> //... //構造函數 ui->textEdit->installEventFilter(this); //this參數表明由本widget部件來負責對 textEdit 的監視和事件過濾 ui->spinBox->installEventFilter(this); //... bool Widget::eventFilter(QObject *watched, QEvent *event) { if( watched == ui->textEdit ){ //第一步:判斷是否是被事件過濾器過濾的對象 if( event->type() == QEvent::Wheel ){ //第二部:判斷是否是需要過濾的事件 QWheelEvent * wheelEvent = static_cast<QWheelEvent*>(event);//第三步:將event強制轉換為發生的事件類型 if(wheelEvent->delta()>0) ui->textEdit->zoomIn(); else ui->textEdit->zoomOut(); return true; //!!!如果需要該事件繼續被傳遞和被處理,返回true。這很重要!!!。 } else return false;//!!!如果不希望該事件繼續被傳遞和被處理,返回false。這很重要!!!。 } else if( watched == ui->spinBox ){ if(event->type() == QEvent::KeyPress){ QKeyEvent * keyEvent = static_cast<QKeyEvent*>(event); if(keyEvent->key() == Qt::Key_Space ){//如果是空格鍵 ui->spinBox->setValue(0); return true; } } else return false; } else return QWidget::eventFilter(watched,event); //最后:返回默認執行結果!!!。 }
[對比前后]
事件發送:
/* *Qt 還提供了 事件發送 的功能,是QCoreApplication類提供的。 * bool QCoreApplication::sendEvent(QObject * receiverObj,QEvent * event); * bool QCoreApplication::postEvent(QObject * receiverObj,QEvent * event,int priority = Qt::NorMalEventPriority); *區別: * sendEvent()立即處理事件;postEvent()把事件放到等待調度隊列中。 * sendEvent()中的QEvent參數對象在事件發送后,自動刪除,所以需要在棧上創建QEvent; * postEvent()中的QEvent參數對象必須new創建,事件發送后,由隊列自動刪除。 * * 下面提供一個例子:構造函數添加代碼,實現想spinBox發送一個向上按鈕觸發事件。 */ QKeyEvent myEvent(QEvent::KeyPress,Qt::Key_Up,Qt::NoModifier);//第三個參數:沒有任何修飾鍵按下 QApplication::sendEvent(ui->spinBox,&myEvent); //
[前后對比]