QMessageBox Output



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

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

这是我的代码,

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_())

如果要根据单击按钮的结果来决定程序的结果,最简单的解决方案是检查exec()方法的结果,该方法返回StandardButton枚举(而不是QDialog通常所做的DialogCode(。

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

相关内容

最新更新