Search code examples
pythonpyqtpyqt4

How to customise a pyqt message box?


pyqt4

msgBox = QtGui.QMessageBox()
msgBox.setText('Which type of answers would you like to view?')
msgBox.addButton(QtGui.QPushButton('Correct'), QtGui.QMessageBox.YesRole)
msgBox.addButton(QtGui.QPushButton('Incorrect'), QtGui.QMessageBox.NoRole)
msgBox.addButton(QtGui.QPushButton('Cancel'), QtGui.QMessageBox.RejectRole)

if msgBox == QtGui.QMessageBox.YesRole:
     Type = 1
      Doc()
elif msgBox == QtGui.QMessageBox.NoRole:
     Type = 0
     Bank()
else:
    ret = msgBox.exec_()

This displays a message box however when an option is clicked, nothing happens and the box closes. How do I get the next function to run?


Solution

  • If the docs are reviewed:

    int QMessageBox::exec()

    Shows the message box as a modal dialog, blocking until the user closes it.

    When using a QMessageBox with standard buttons, this functions returns a StandardButton value indicating the standard button that was clicked. When using QMessageBox with custom buttons, this function returns an opaque value; use clickedButton() to determine which button was clicked.

    Note: The result() function returns also StandardButton value instead of QDialog::DialogCode

    Users cannot interact with any other window in the same application until they close the dialog, either by clicking a button or by using a mechanism provided by the window system.

    See also show() and result().

    So as you recommend you must use clickedButton(), as I show below:

    from PyQt4 import QtGui
    import sys
    
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
    
        msgBox = QtGui.QMessageBox()
        msgBox.setText('Which type of answers would you like to view?')
        correctBtn = msgBox.addButton('Correct', QtGui.QMessageBox.YesRole)
        incorrectBtn = msgBox.addButton('Incorrect', QtGui.QMessageBox.NoRole)
        cancelBtn = msgBox.addButton('Cancel', QtGui.QMessageBox.RejectRole)
    
        msgBox.exec_()
    
        if msgBox.clickedButton() == correctBtn:
            print("Correct")
        elif msgBox.clickedButton() == incorrectBtn:
            print("Incorrect")
        elif msgBox.clickedButton() == cancelBtn:
            print("Cancel")