PDA

View Full Version : QApplication handle all event, why does not include QKeyEvent?



royt
20th July 2012, 08:01
My Qt GUI application has a main dialog, and I want all key event to be processed in the dialog but not its children widgets (event they get focus), so I install a event filter for qApp in main():

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

Then in MyDialog.cpp:

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

I set 2 breakpoints. During debugging, the breakpoint 2 can be reached, it means that qApp dispatch events to dialog's eventfilter. But breakpoint 1 never been reached when I press any key. Why the QKeyevent not handled in qApp ?

ChrisW67
20th July 2012, 08:40
From the friendly docs:

Key events are sent to the widget with keyboard input focus when keys are pressed or released.
Your filter will see the key press events but they are not directed at the QApplication instance, i.e. watched != qApp.

royt
20th July 2012, 09:13
From the friendly docs:

Your filter will see the key press events but they are not directed at the QApplication instance, i.e. watched != qApp.


I thought when a widget in main dialog get focus, then press key, the QKeyEvent should be handled by qApp, then forward to the focused widget. That is, qApp handle all events and be responsible for dispatching them, am I wrong ?

I want process all key press event for all widgets in main dialog, so I don't want to install event filter for every children widgets one by one.

high_flyer
20th July 2012, 10:09
I thought when a widget in main dialog get focus, then press key, the QKeyEvent should be handled by qApp, then forward to the focused widget.
This is almost correct.
The system key event is handled by QApplication, but that event is not yet a QEeyEvent.
QApplication will create and dispatch a QKeyEvent if there is a widget that has to handle it (at least that is the way I understand it).
You might want to use QCoreApplication::winEventFilter().
And you might want to read about QAbstractEventDispatcher.

royt
20th July 2012, 12:41
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.