2
QApplication app(argc, 0);
MyDialog * pDlg = new MyDialog(0, Qt::WindowTitleHint | Qt::CustomizeWindowHint);
if (qApp) qApp->installEventFilter(pDlg);

In main(), I just install a event filter for qApp. Then in MyDialog.cpp:

bool MyDialog::eventFilter(QObject * watched, QEvent * event)
{
    if (watched == qApp)
    {
        if (event->type() == QEvent::KeyPress)
        {
            // do something
            return true;
        }
        return false;
    }
    return QDialog::eventFilter(watched, event);
}

I set some breakpoints. the line "return false" can be reached, it means the qApp had successfully installed a event filter at MyDialog. But line 'return true' never reached when I press keyboard. I remember that QApplication will dispatch all event. Could anybody tell me why this happened?

Royt
  • 199
  • 4
  • 14

1 Answers1

1

Use keyPressEvent.

void MyDialog::keyPressEvent(QKeyEvent *e)
{
// do something
}
ScarCode
  • 3,074
  • 3
  • 19
  • 32
  • 2
    I made a stupid mistake. if (watched == qApp) is wrong, the "watched" is the obj that is ready to receive the event, but not the qApp whose events are forword to the watcher. – Royt Jul 20 '12 at 10:39