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?
QDialog has a private slot called
accept()
. Whenever QDialogButtonBox emitsaccepted()
(by pressing return key or clicking Ok), that private slot is called. So try disconnecting them.disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
This worked for me.
The problem is the event filter shouldn't be installed on the OK button.
If your OK button is disabled, then it's not going to receive the enter event. Whichever widget has the focus will. And if they don't accept the enter event, then
QDialog
is going toaccept()
itself.Two ways to solve the problem:
1) Override
QDialog::accept()
, and callQDialog
's accept method in the newaccept
function only if OK is enabled2) Install an event filter on every widget in the dialog that doesn't accept the enter key (line edits, ...).
The event filter would be like so:
And in your code, for each widget in the dialog:
To avoid "OK" button or "Enter" key from closing dialog: in the ui xml file, remove the connect/slot for accept/reject. Then, in your code , emmit accept() when and as needed;
example from ui file which connects accept() slot:
If you have normal QPushButtons on the dialog then if the buttons have the autoDefault and/or default properties set on them then you get a default button - which is what the enter key triggers. In that case, get rid of autoDefault on the buttons and pressing enter in another widget no longer closes the dialog.
In the case of a QDialogButtonBox you can probably iterate over the buttons to turn this stuff off in the ctor of your dialog. Not tested here but ought to work. If not then you'll need to also see if there is a default button that gets set on the QDialog itself too.
In PySide (and I imagine PyQt) I was able to redefine the accept and reject functions of the QDialog.
This kept the file dialog from closing and gave me access to the data when the 'ok' (accept) or 'cancel' (reject) functions were triggered (either with enter or by clicking the buttons)
The key press event filtering should be done on the dialog itself, because the code handling the forwarding of the
Return
andEnter
keys to the default button is inQDialog::keyPressEvent
.Or