問題描述
我目前正在學(xué)習(xí)如何使用 pyqt5 構(gòu)建應(yīng)用程序,但遇到了 closeEvent 方法的一些問題,已被覆蓋,因此 QMessageBox 對象要求用戶確認(rèn).它似乎與 X 按鈕配合得很好——當(dāng)操作被確認(rèn)時,事件被接受",當(dāng)點擊取消按鈕時,事件被取消".但是,當(dāng)我從下拉文件菜單中使用退出按鈕時,無論我單擊哪個按鈕,程序都會以退出代碼 1 關(guān)閉.看起來很奇怪,因為我在兩種情況下都使用相同的 closeEvent 方法.
I'm currently learning how to build an application with pyqt5 and encountered some problem with closeEvent method, overriden so user gets asked for confirmation by QMessageBox object. It seems working well with X button - event gets 'accepted' when action is confirmed and 'canceled' when cancel button is clicked. However, when I use my Quit button from dropdown File menu, no matter which button I click, program gets closed with exit code 1. Seems strange, because I use same closeEvent method in both cases.
import sys
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QAction
class window(QMainWindow):
def __init__(self):
super().__init__()
def createUI(self):
self.setGeometry(500, 300, 700, 700)
self.setWindowTitle("window")
quit = QAction("Quit", self)
quit.triggered.connect(self.closeEvent)
menubar = self.menuBar()
fmenu = menubar.addMenu("File")
fmenu.addAction(quit)
def closeEvent(self, event):
close = QMessageBox()
close.setText("You sure?")
close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
close = close.exec()
if close == QMessageBox.Yes:
event.accept()
else:
event.ignore()
main = QApplication(sys.argv)
window = window()
window.createUI()
window.show()
sys.exit(main.exec_())
感謝您的建議!
推薦答案
當(dāng)您單擊按鈕時,程序會調(diào)用您的函數(shù),但使用不同的 event
對象,該對象沒有 accept()
和 ignore()
所以你會收到錯誤消息并且程序以退出代碼 1 結(jié)束.
When you click button then program calls your function but with different event
object which doesn't have accept()
and ignore()
so you get error message and program ends with exit code 1.
您可以分配 self.close
并且程序?qū)⑹褂谜_的事件對象調(diào)用 closeEvent()
.
You can assign self.close
and program will call closeEvent()
with correct event object.
quit.triggered.connect(self.close)
這篇關(guān)于PyQt5 closeEvent 方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!