1

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?

Bart
  • 19,692
  • 7
  • 68
  • 77
Royt
  • 199
  • 4
  • 14

1 Answers1

0

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.

ScarCode
  • 3,074
  • 3
  • 19
  • 32
  • If a widget (eg. button) get focus, then pressing a key, the focused widget's keyPress event will be called, and won't handle to its parent. I think maybe the qApp dispatch the event to the right destination (focused widget). – Royt Jul 19 '12 at 16:24
  • Thanks for your reply. OverWrite children widget's event process method or install a event filter could do. but in the main diloag, there are many widgets, so a lot of code will be written and the structure is not good. I think I should handle the key event where all events are ready to dispatched. – Royt Jul 20 '12 at 06:26