生成QCloseEvent不会关闭QMainWind

2024-04-24 09:57:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一些非常简单的事情:添加一个带有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>

应用程序确实退出。在

这是在Windows7 64位、Python2.7.2、PyQt 4.8.6上实现的。在


Tags: selfevent应用程序sysexitbaractionwindow
2条回答

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

关闭事件实际上并不会使窗口关闭,它只是在窗口已经关闭时触发的。要真正关闭窗口,需要调用self.close(),这将产生触发QCloseEvent的副作用。所以简单地使用这个:

 exit_action.triggered.connect(self.close)

documentation of ^{}描述了close和{}之间的交互作用:

bool QWidget.close (self)

This method is also a Qt slot with the C++ signature bool close().

Closes this widget. Returns true if the widget was closed; otherwise returns false.

First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget.closeEvent() accepts the close event.

相关问题 更多 >