温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - QMessageBox add custom button and keep open
pyqt pyqt5 python python-3.x qmessagebox

python - QMessageBox添加自定义按钮并保持打开状态

发布于 2020-03-27 10:32:49

我想向QMessagebox添加一个自定义按钮,以打开一个matplotlib窗口,以及一个Ok按钮,供用户在要关闭它时单击

我目前有一些工作,但我希望这两个按钮可以做一些单独的事情,而不是打开窗口。

我知道我可以使用所需的结果创建一个对话框,但是我想知道如何使用QMessageBox。

import sys
from PyQt5 import QtCore, QtWidgets

def main():
    app = QtWidgets.QApplication(sys.argv)
    msgbox = QtWidgets.QMessageBox()
    msgbox.setWindowTitle("Information")
    msgbox.setText('Test')
    msgbox.addButton(QtWidgets.QMessageBox.Ok)
    msgbox.addButton('View Graphs', QtWidgets.QMessageBox.YesRole)

    bttn = msgbox.exec_()

    if bttn:
        print("Ok")
    else:
        print("View Graphs")
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

所需结果:

确定按钮-关闭QMessageBox

“查看图”按钮-打开matplotlib窗口并保持QMessageBox打开,直到用户单击“确定”为止

查看更多

查看更多

提问者
Drees
被浏览
511
musicamante 2019-07-03 21:32

与所有QDialogs一样,QMessageBox会阻塞所有内容,直到exec_()返回为止,但它还会自动将所有按钮连接到已接受/已拒绝的信号,exec_()无论如何都将返回

您的代码可能的解决方案是:

app = QtWidgets.QApplication(sys.argv)
msgbox = QtWidgets.QMessageBox()
# the following is if you need to interact with the other window
msgbox.setWindowModality(QtCore.Qt.NonModal)
msgbox.addButton(msgbox.Ok)
viewGraphButton = msgbox.addButton('View Graphs', msgbox.ActionRole)
# disconnect the clicked signal from the slots QMessageBox automatically sets
viewGraphButton.clicked.disconnect()

# this is just an example, replace with your matplotlib widget/window
graphWidget = QtWidgets.QWidget()

viewGraphButton.clicked.connect(graphWidget.show)
msgbox.button(msgbox.Ok).clicked.connect(graphWidget.close)
# do not use msgbox.exec_() or it will reset the window modality
msgbox.show()
sys.exit(app.exec_())

也就是说,请谨慎使用QDialog.exec_()外部sys.exit(app.exec_())呼叫(如“之前”),因为如果您不知道自己在做什么,可能会导致意外行为。