我是PyQT的新手。我正在将我的应用程序之一从tkinter转移到PyQT。我想要的是以下情况:当用户单击X按钮时,在主屏幕仍处于打开状态时,将出现询问用户是否确定关闭的消息框。然而,在我的代码,X按钮被点击时,主屏幕上消失第一和消息框出现。我该如何解决这个“订单问题”?我的代码如下:
(在Tkinter的,这是很容易的代码root.protocol("WM_DELETE_WINDOW", on_closing)
,并含有on_closing函数messagebox.askokcancel("Quit", "Do you want to quit Chit-Chat?")
命令,但是,我不能完全弄清楚在PyQt的。)
app = QApplication(sys.argv)
v_box = QVBoxLayout()
window = QWidget()
label = QLabel("Hello World")
v_box.addWidget(label)
def closeEvent():
msg_box = QMessageBox()
choice = QMessageBox.question(msg_box, "Quit", "Do you want to quit chit chat?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
print("The program was shut down.")
sys.exit()
else:
pass
app.aboutToQuit.connect(closeEvent)
window.setLayout(v_box)
window.show()
sys.exit(app.exec())
答案 0 :(得分:0)
您可以选择是否接受活动。
def closeEvent(self, event):
if self.popup_question():
print("The program was shut down.")
event.accept()
else:
print("not exiting")
event.ignore()
def popup_question(self):
"""Generate a popup that requests if you want to do something or not."""
msgbox = QtWidgets.QMessageBox()
msgbox.setWindowTitle("Whatever title you want to add.")
msgbox.setIcon(QtWidgets.QMessageBox.Warning)
msgbox.setText("Do you want to quit chit chat?")
botonyes = QtWidgets.QPushButton("Yes")
msgbox.addButton(botonyes, QtWidgets.QMessageBox.YesRole)
botonno = QtWidgets.QPushButton("No")
msgbox.addButton(botonno, QtWidgets.QMessageBox.NoRole)
msgbox.exec_()
if msgbox.clickedButton() == botonno:
return False
else:
return True
答案 1 :(得分:0)
尝试:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
label = QLabel("Hello World")
v_box = QVBoxLayout()
v_box.addWidget(label)
self.setLayout(v_box)
def closeEvent(self, event):
choice = QMessageBox.question(
self,
"Quit",
"Do you want to quit chit chat?",
QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
print("The program was shut down.")
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
qt_app = Window()
qt_app.show()
sys.exit(app.exec_())
答案 2 :(得分:0)
使用functools
覆盖窗口的窗口小部件closeEvent
而不创建子类,然后使用event.accept()
或event.ignore()
接受或取消关闭事件:
import functools
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QLabel, QMessageBox
def closeEvent(self, event):
choice = QMessageBox.question(self, "Quit", "Do you want to quit chit chat?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
event.accept()
else:
event.ignore()
app = QApplication(sys.argv)
v_box = QVBoxLayout()
window = QWidget()
window.closeEvent = functools.partial(closeEvent, window)
label = QLabel("Hello World")
v_box.addWidget(label)
window.setLayout(v_box)
window.show()
sys.exit(app.exec())