示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class MainWindow : public QMainWindow {
public:
MainWindow();

protected:
bool eventFilter(QObject *obj, QEvent *ev) override;

private:
QTextEdit *textEdit;
};

MainWindow::MainWindow() {
textEdit = new QTextEdit;
setCentralWidget(textEdit);

textEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
}
else {
return false;
}
}
else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}

注册事件过滤器的参数是需要重写eventFilter的那个类的指针,未处理的事件传递给基类。

Notice in the example above that unhandled events are passed to the base class’s eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.