gpt4 book ai didi

python - 生成 QCloseEvent 不会关闭 QMainWindow

转载 作者:行者123 更新时间:2023-12-01 05:02:45 25 4
gpt4 key购买 nike

我正在尝试做一些非常简单的事情:添加一个带有 Exit 操作的菜单栏,该操作将在选择时关闭 QMainWindow 。但是,当我实际单击 Exit 时,它不会关闭应用程序。 SSCCE:

from PyQt4 import QtGui, QtCore

import sys

class Window(QtGui.QMainWindow):

def __init__(self, parent=None):
super(Window, self).__init__(parent)
widget = QtGui.QWidget()
self.setCentralWidget(widget)

self.menu_bar = QtGui.QMenuBar(self)
menu = self.menu_bar.addMenu('File')

exit_action = QtGui.QAction('Exit', self)
exit_action.triggered.connect(lambda:
self.closeEvent(QtGui.QCloseEvent()))
menu.addAction(exit_action)
self.setMenuBar(self.menu_bar)

def closeEvent(self, event):
print('Calling')
print('event: {0}'.format(event))
event.accept()


app = QtGui.QApplication(sys.argv)
form = Window()
form.show()
sys.exit(app.exec_())

真正让我困惑的是,当我从 File 菜单中单击 Exit 时,我得到以下输出:

Calling

event: <PyQt4.QtGui.QCloseEvent object at 0x024B7348>

并且应用程序不会退出。

如果我点击右上角的X,我会得到同样的结果(直到事件对象的相同内存地址):

Calling

event: <PyQt4.QtGui.QCloseEvent object at 0x024B7348>

并且应用程序确实退出。

此版本适用于 Windows 7 64 位、Python 2.7.2、PyQt 4.8.6。

最佳答案

文档says ,

The QCloseEvent class contains parameters that describe a close event.

Close events are sent to widgets that the user wants to close, usually by choosing "Close" from the window menu, or by clicking the X title bar button. They are also sent when you call QWidget.close() to close a widget programmatically.

您可以直接使用信号关闭来调用,而不是通过QCloseEvent来调用,请调用self.close()

from PyQt4 import QtGui, QtCore

import sys

class Window(QtGui.QMainWindow):

def __init__(self, parent=None):
super(Window, self).__init__(parent)
widget = QtGui.QWidget()
self.setCentralWidget(widget)

self.menu_bar = QtGui.QMenuBar(self)
menu = self.menu_bar.addMenu('File')

exit_action = QtGui.QAction('Exit', self)
exit_action.triggered.connect(self.close)
menu.addAction(exit_action)
self.setMenuBar(self.menu_bar)

def closeEvent(self, event):
print('Calling')
print('event: {0}'.format(event))
event.accept()


app = QtGui.QApplication(sys.argv)
form = Window()
form.show()
sys.exit(app.exec_())

关于python - 生成 QCloseEvent 不会关闭 QMainWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com