Thursday, May 17, 2007

QObject.eventFilter

bool QObject.eventFilter (self, QObject, QEvent)

Filters events if this object has been installed as an event filter for the watched object.

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

Example:

 class MainWindow : public QMainWindow
{
public:
MainWindow();

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

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(event);
qDebug() << "Ate key press" <<>key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow.eventFilter(obj, event);
}
}

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.

Warning: If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.

See also installEventFilter().

No comments: