pythonpyqtpyqt5qmessagebox

How to put an event on the buttons of QMessageBox


I just want to set an event on the yes button of the message box but when I click the yes button it returns me None value and it not satisfies the condition.

def question(self):
    msg = QMessageBox()
    result = msg.setStandardButtons(msg.Yes | msg.No)
    msg.setIcon(msg.Question)
    msg.setText(self.text)
    msg.setWindowTitle('Console')

    if result == msg.Yes:
        print('Yes')

    msg.exec_()

Solution

  • setStandardButtons() is a setter and returns nothing, the logic is actually to get the button clicked and then get the associated QMessageBox::StandardButton.

    def question(self):
        msg = QMessageBox()
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg.setIcon(msg.Question)
        msg.setText(self.text)
        msg.setWindowTitle('Console')
        msg.exec_()
        button = msg.clickedButton()
        sb = msg.standardButton(button)
        if sb == QMessageBox.Yes:
            print("YES")