How do I prevent the enter key from closing my QDialog (Qt 4.8.1)

cppguy picture cppguy · Apr 6, 2013 · Viewed 17.4k times · Source

I have a QDialog with a QDialogButtonBox. The OK and Cancel buttons are active. Occasionally I disable or hide the OK button based on the state of my dialog. It seems, no matter what I do, the Enter key always activates the OK button. I really DON'T want this to happen. I have tried:

  • Setting default and autoDefault properties to false every time I show/hide/enable/disable/whatever the button
  • installing an event filter on the OK button to intercept key events (pressed and released) for return, enter and space
  • Setting the focus policy on the button to NoFocus

And with all combinations of those things above, the Enter key still accepts the dialog. Does anyone have any clue how to block this? It seems like I should be able to block something as simple as this?

Answer

alexisdm picture alexisdm · Apr 6, 2013

The key press event filtering should be done on the dialog itself, because the code handling the forwarding of the Return and Enter keys to the default button is in QDialog::keyPressEvent.

void Dialog::keyPressEvent(QKeyEvent *evt)
{
    if(evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return)
        return;
    QDialog::keyPressEvent(evt);
}

Or

theDialog−>installEventFilter(anotherClassObject);

bool AnotherClass::eventFilter(QObject *obj, QEvent *evt)
{
    if(evt->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(evt);
        if(keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return )
            return true; // mark the event as handled
    }
    return false;
}