1
votes

I have a QMainWindow with an event filter installed that opens a QDialog. The main window handles the key release of the Enter key. But, when I press the Enter key while the QDialog is open and in focus the main window also catches this event.

How can I prevent that from happening? I tried to install an event filter in the QDialog, to reimplement the keyReleaseEvent and keyPressEvent functions, change the parent (which is currently 0), but nothing seems to help...

Note that when I change the event filter of the QMainWindow such that it handles key press instead of key release the QDialog works fine, but then I get other bugs that I'm trying to avoid...

bool Window::eventFilter(QObject *, QEvent *event) {
 if (type == QEvent::KeyRelease) {
   QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

   switch(keyEvent->key()) {
   case Qt::Key_Enter:
     // do something here
     break;
   default:
     break;
   }
}

Dialog::Dialog(unsigned int num, QWidget *parent)
: QDialog(parent), num(_num)
{
   ui.setupUi(this);
   ui.btnOK->setEnabled(false);

   connect(ui.btnOK, SIGNAL(clicked()), this, SLOT(accept()));
   connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(reject()));

   installEventFilter(this);
}

bool Dialog::eventFilter(QObject *, QEvent *event) {
 return true;
} 

Thanks in advance

1

1 Answers

2
votes

Try webclectic's first approach, but replace e->ignore() with e->accept(), since ignore()'s behaviour is opposite to what you want to achieve.

void MyDialog::keyReleaseEvent(QKeyEvent* e)
{
    QDialog::keyReleaseEvent(e);
    if (e->key() == Qt::Key_Enter)
        e->accept();
}

Or maybe you should try modal dialog?

UPDATE: We must always call QDialog's implementation if we want the dialog to respond to Enter key release.