QObject 有一个事件过滤器接口: bool eventFilter(QObject *Watch , QEvent *event);
重写的时候发现,obj是要监视的控件 ,如果是此控件且事件相符则执行相应操作,且返回true
否则返回false
如果不是要监视的控件,则一定继续投递事件
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);
}
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.
QObject *A
QObject *B
将B设置为A的事件过滤波器
A.installEventFilter(B)
B要重写eventFilter()