Question

I have a dialog inherits QDialog. the dialog has many widgets including Qbuttons, QLabel, QGraphicsView, etc. Many widgets such as button can process SPACE key pressing event when they get focus. Now I don't want any of the child widgets to deal with it, but let the main dialog do. Since there are many widgets in main dialog,so I didn't intallEventFilter for them, but for qApp.

code as follow:

QApplication app(argc, 0);
MyDialog *pDlg = new MyDialog(...);
qApp->installEventFilter(pDlg);
app.exec();

And eventfilter of main dialog:

bool MyDialog::eventFilter(QObject *obj, QEvent *e)
{
    if(e->type() == QEvent::KeyPress)
    {
        QKeyEvent *ke = static_cast<QKeyEvent*>(e);
        if (ke->key == Qt::Key_Space && !ke->isAutoRepeat())
        {
            // do my things in the main dialog
            return true;
        }
    }
    return qApp->eventFilter(watched, event);
}

Unfortunately, after using this code, the main dialog's layout is curious, seems some widgets didn't remember their size policy. Maybe some Qt resize or repaint event not processed? Could any one tell me how to catch the key event in main dialog, but not affect other function?

Was it helpful?

Solution

Basically if you developing a dialog based App in Qt, by default keypress events are captured by main dialog class, provided you define keypressevent in the main class.

EDIT Use postevent() for this purpose

In your child widgets key press event do

void childwdgt::keyPressEvent(QKeyEvent *e)
{
if (e->type() == QEvent::KeyPress)
{
    {
        QKeyEvent* newEvent = new QKeyEvent(QEvent::KeyPress,e->key(), e->modifiers ());
        qApp->postEvent (yourParentWdgt, newEvent, 0);
    }
}

Similarly you can handle other type of key events also.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top