pythonpython-2.7pyqtpyqt4qdialog

How to change the default button behaviour in a QDialog


I read that QDialog has as default all its objects set as default. For example if I add a QPushButton:

pushButton.setDefault(True)   
pushButton.setAutoDefaul(True)

I know that I can set each one as False, but is there a way of avoiding QDialog setting all its objects as default?


Solution

  • Actually, setting the default to False for all the buttons will have no affect. If no button has been set as the default, the dialog will just choose one automatically - so there will always be a default, no matter what you do.

    You can change this behaviour by overriding the dialog's keyPressEvent:

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Cancel):
            self.reject()
        else:
            event.ignore()
    

    This completely overrides the default-button behaviour, but retains cancellation of the dialog when e.g. Esc is pressed. If you don't want that either, just call event.ignore(), which will allow all keypress events to propagate to the current focus-widget. Thus, pressing Enter or Return when a button or line-edit has the focus will still activate it as normal. The default-button mechanism only comes into play when some other widget has the focus but does not swallow the keypress event (e.g. when pressing Return in a line-edit).