umbe1987 umbe1987 - 1 month ago 13
Python Question

Use QMessageBox in PyQt5 to restart my game or exit the application

I have a memory game made in PyQt5. When the user wins, I'd like to show a message with three options (buttons):


  1. 'play again'

  2. 'change cards'

  3. 'quit'



I think the way to implement this is by using a QMessageBox, but I could not understand how to use it properly. I know it has to be something like:

reply = QMessageBox.question(self,
'title',
'text',
button1 | button2 | button3,
defaultButton)

if reply == button1:
# play again
elif reply == button2:
# change cards
else:
# close application


I also know there exist
StandardButtons
, which I can use for exiting (
QMessageBox.Close
, but I am not sure), but I don't know how can I add them and other custom buttons in order to have it working.

EDIT 1

Ok, I think I made some steps towards the right direction, although something is stil missing.
I was able to add custom buttons to my
QMessageBox
, I am able to
print
something when one of them is clicked, but any method I call after is not doing anything. Also, if 'quit' is selected, it just closes the message box (I am using the
QCloseEvent
method, maybe it's wrong).

Here is the updated code, along with few comments:

msgBox = QMessageBox()
msgBox.setStandardButtons(QMessageBox.Close)
restartBtn = msgBox.addButton('play again', QMessageBox.ActionRole)
changeBtn = msgBox.addButton('change cards', QMessageBox.ActionRole)

ret = msgBox.exec()

if ret == QMessageBox.Close:
QCloseEvent() # should close the app, but it closes the message box
elif msgBox.clickedButton() == restartBtn:
print('RESTART')
self.restart # should call 'restart' method, but it doesn't
elif msgBox.clickedButton() == changeBtn:
print('CHANGE')
changeBtn.clicked.connect(self.showDialog) # should call 'showDialog' method, but it doesn't


As you can see, I tried both with
self.methodname
and with
button.clicked.connect(self.methodname)
, but none worked.

Answer

You seem to have worked out most of it already, but here's a complete example:

def showMessageBox(self):
    msg = QtWidgets.QMessageBox(self)
    msg.setIcon(QtWidgets.QMessageBox.Question)
    msg.setWindowTitle('Prompt')
    msg.setText('Please choose an option:')
    play = msg.addButton(
        'Play Again', QtWidgets.QMessageBox.AcceptRole)
    change = msg.addButton(
        'Change Cards', QtWidgets.QMessageBox.AcceptRole)
    quit = msg.addButton(
        'Quit', QtWidgets.QMessageBox.RejectRole)
    msg.setDefaultButton(play)
    msg.exec_()
    msg.deleteLater()
    if msg.clickedButton() is play:
        print('RESTART')
        self.restart()
    elif msg.clickedButton() is change:
        print('CHANGE')
        self.showDialog()
    else:
        self.close()
Comments