Search code examples
pythonpyqtpyqt5qmessagebox

How to change button focus on QMessageBox?


I am using a QMessageBox to get get a Yes or No answer from the user as follows:

msgbox = QMessageBox.question(self, 'Title', 'Question', QMessageBox.Yes | QMessageBox.No)

With this implementation the default focus is on the 'No' button. How can I change it to default to 'Yes' to make it easier to accept with a 'Return' keystroke rather than having to actually click on the 'Yes' button?


Solution

  • The "defaultButton" parameter indicates the button that has the focus initially:

    msgbox = QMessageBox.question(
        self,
        "Title",
        "Question",
        buttons=QMessageBox.Yes | QMessageBox.No,
        defaultButton=QMessageBox.Yes,
    )