尽管在closeEvent上有event.accept,QMainWindow.close也不会关闭窗口

时间:2013-04-01 10:38:44

标签: python qt pyqt

我正在尝试编写一个使用QMainWindow的应用程序,并在那里使用带有File-> Exit功能的QMenuBar,它也使用UIC文件。我已经将我的项目剥离到尽管我的努力不起作用的部分 - 调用closeEvent,它被接受,但窗口没有关闭。这是我的test.py:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function

import sys
from PyQt4 import QtCore, QtGui, uic

class TruEdit(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QDialog.__init__(self)

        self.ui = uic.loadUi("test.ui")
        self.ui.show()

        self.ui.actionWyj_cie.triggered.connect(self.wyjscie)

    def wyjscie(self):
        self.close()

    def closeEvent(self, event):
        event.accept()
        print("WTF, still alive")

    @QtCore.pyqtSlot()
    def reject(self):
        print("Never entered this")
        return None


if __name__=="__main__":
    app = QtGui.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    window = TruEdit()
    sys.exit(app.exec_())

这是test.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>

  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>21</height>
    </rect>
   </property>

   <widget class="QMenu" name="menuPlik">
    <property name="title">
     <string>Plik</string>
    </property>
    <addaction name="actionWyj_cie"/>
   </widget>
   <addaction name="menuPlik"/>
  </widget>
  <widget class="QStatusBar" name="statusbar">
   <property name="statusTip">
    <string/>
   </property>
  </widget>
  <action name="actionWyj_cie">
   <property name="text">
    <string>Wyjście</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+K</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您可以在这里找到更好的答案

PyQt: clicking X doesn't trigger closeEvent

问题似乎在于,

    self.ui = uic.loadUi("test.ui")
    self.ui.show()

创建名为self.ui的实例

答案 1 :(得分:0)

在我看来,你正在覆盖closeEvent,然后在其中做任何事情。调用event.accept()实际上并不执行该事件。它只是告诉事件对象它已被接受,以便事件不会继续传播。在C ++领域,你需要做这样的事情

void closeEvent(QCloseEvent *Event) {
    // do some stuff
    QMainWindow::closeEvent(event);
}

请注意对QMainWindow的关闭事件的调用,这是实际关闭窗口的代码所在的位置。

相关问题