[英]Use QMessageBox in PyQt5 to restart my game or exit the application
我有一個用PyQt5制作的記憶游戲。 當用戶獲勝時,我想顯示一條帶有三個選項(按鈕)的消息:
我認為實現此目的的方法是使用QMessageBox,但我不明白如何正確使用它。 我知道必須是這樣的:
reply = QMessageBox.question(self,
'title',
'text',
button1 | button2 | button3,
defaultButton)
if reply == button1:
# play again
elif reply == button2:
# change cards
else:
# close application
我也知道存在StandardButtons
,我可以使用它退出( QMessageBox.Close
,但我不確定),但是我不知道如何添加它們和其他自定義按鈕以使其正常工作。
編輯1
好的,我想我朝着正確的方向邁出了一步,盡管仍然缺少一些東西。 我可以在QMessageBox
添加自定義按鈕,單擊其中一個按鈕時,我可以print
某些內容,但是之后調用的任何方法都沒有執行任何操作。 另外,如果選擇了“退出”,它只會關閉消息框(我正在使用QCloseEvent
方法,也許是錯誤的)。
這是更新的代碼,以及一些注釋:
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
如您所見,我同時嘗試了self.methodname
和button.clicked.connect(self.methodname)
,但是都沒有用。
您似乎已經解決了大部分問題,但這是一個完整的示例:
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()
最終,我意識到我所做的幾乎是正確的,除了在調用方法之后缺少括號。 現在,代碼可以正常運行,除了單擊“退出”時(不顯示消息框)它不會退出應用程序外,但我會盡快找到答案。 希望對於任何想要實現自己的QMessageBox
人來說,這都是一個很好的例子。
最后一點:我嘗試過的兩種方法(即調用方法本身或通過在button.clicked.connect()
方法前添加前綴button.clicked.connect()
對我有效。 也許一個比另一個更好,但我認為。
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()
elif msgBox.clickedButton() == changeBtn:
print('CHANGE')
changeBtn.clicked.connect(self.showDialog())
self.close用作關閉整個應用程序的方法。
button.clicked.connect(self.close)
choice = QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Quit)
if choice == QtGui.QMessageBox.Quit:
self.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.