祝大家今天愉快,我正在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_())发布于 2020-05-19 21:36:17
如果要根据单击按钮的结果来决定程序的结果,最简单的解决方案是检查exec()方法的结果,该方法返回StandardButton枚举(而不是QDialog通常所做的DialogCode )。
def close_func1(self): # Ask Yes | No Question
# ...
x = msg.exec()
if x == msg.Yes:
QApplication.quit()https://stackoverflow.com/questions/61901048
复制相似问题