【问题标题】:QMessageBox OutputQMessageBox 输出
【发布时间】:2020-05-19 21:26:22
【问题描述】:

祝大家有个美好的一天, 我正在尝试在menuBar() 中创建一个退出按钮。我的意思是,当用户点击关闭按钮时,QMessageBox() 会弹出来询问QMessageBox.Yes | QMessageBox.No。根据信号,我想关闭程序。

为了测试代码,我只使用print()。但是结果是 &No 或 &Yes,而不仅仅是 No 或 Yes。这是什么原因?我想不通。

这是我的代码,

from PyQt5.QtWidgets import *
import sys


class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        self.ui()
        self.menu()

        self.show()

    def ui(self):
        self.setWindowTitle("Basic")
        self.setGeometry(100, 50, 1080, 640)

    def menu(self):
        mainmenu = self.menuBar()
        filemenu = mainmenu.addMenu("File")

        file_close = QAction("Close", self)
        file_close.setShortcut("Ctrl+Q")
        file_close.triggered.connect(self.close_func1)

        filemenu.addAction(file_close)

    def close_func1(self):  # Ask Yes | No Question
        msg = QMessageBox()
        msg.setWindowTitle("Warning!")
        msg.setText("Would you like to exit ?")
        msg.setIcon(QMessageBox.Question)
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg.setDefaultButton(QMessageBox.No)
        msg.buttonClicked.connect(self.close_func2)
        x = msg.exec()

    def close_func2(self, i):  # In this section code decide to close it or not with if statement
        print(i.text())


app = QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())

【问题讨论】:

  • 如果有更好的方法来实现我的目标,我会很高兴听到这个消息。

标签: python-3.x pyqt5 qmessagebox


【解决方案1】:

如果你想根据点击按钮的结果来决定程序的结果,最简单的解决方案是检查exec()方法的结果,它返回一个StandardButton枚举(而不是 DialogCode 就像 QDialog 通常那样)。

    def close_func1(self):  # Ask Yes | No Question
        # ...
        x = msg.exec()
        if x == msg.Yes:
            QApplication.quit()

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2012-09-07
    相关资源
    最近更新 更多