closeEvent是QMainwindow的一种方法,但是您试图从自己的Ui_MainWindow类中使用它。请改为:from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):

def __init__(self, *args, **kwargs):

super(MainWindow, self).__init__(*args, **kwargs)

self.setupUi()

def setupUi(self):

self.setObjectName("MainWindow")

self.resize(277, 244)

self.statusbar = QtGui.QStatusBar()

self.statusbar.setObjectName("statusbar")

self.setStatusBar(self.statusbar)

def closeEvent(self,event):

result = QtGui.QMessageBox.question(self,

"Confirm Exit...",

"Are you sure you want to exit ?",

QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)

event.ignore()

if result == QtGui.QMessageBox.Yes:

event.accept()

if __name__ == "__main__":

import sys

app = QtGui.QApplication(sys.argv)

mainWindow = MainWindow()

mainWindow.show()

sys.exit(app.exec_())

如果您希望尽可能多地保留结构,请尝试以下操作:from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):

def setupUi(self, MainWindow):

MainWindow.setObjectName("MainWindow")

MainWindow.resize(277, 244)

self.centralwidget = QtGui.QWidget(MainWindow)

self.centralwidget.setObjectName("centralwidget")

MainWindow.setCentralWidget(self.centralwidget)

self.statusbar = QtGui.QStatusBar(MainWindow)

self.statusbar.setObjectName("statusbar")

MainWindow.setStatusBar(self.statusbar)

QtCore.QMetaObject.connectSlotsByName(MainWindow)

MainWindow.show()

class MyWindow(QtGui.QMainWindow):

def closeEvent(self,event):

result = QtGui.QMessageBox.question(self,

"Confirm Exit...",

"Are you sure you want to exit ?",

QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)

event.ignore()

if result == QtGui.QMessageBox.Yes:

event.accept()

if __name__ == "__main__":

import sys

app = QtGui.QApplication(sys.argv)

MainWindow = MyWindow()

ui = Ui_MainWindow()

ui.setupUi(MainWindow)

sys.exit(app.exec_())

closeEvent是QMainwindow的一种方法,但是您试图从自己的Ui_MainWindow类中使用它。请改为:from PyQt4 import QtCore, QtGuiclass MainWindow(QtGui.QMainWindow):def __init__(self, *args, **kwargs):super(MainWindow, self).__init__(*arg...
PyQt 5关闭主窗口的同时关闭所有子窗口 重写相关控件的父类的 close Event ()方法即可. 示例代码如下: 重写Q Main Window 类的 close Event ()方法 import sys from PyQt 5.QtWidgets import (Q Main Window , QPushButton, QApplication, QWidget, QMessageBox) from PyQt 5.QtCore import (QCoreApplic
您可以使用Q Close Event 事件来监控是否点击了关闭按钮。您可以重写QWidget或Q Main Window close Event ()方法,以便在关闭窗口之前执行一些操作。例如: ``` python class MyWidget(QWidget): def close Event (self, event ): # 在这里执行您的操作 print("窗口关闭了") event .accept() # 关闭窗口 if __name__ == '__ main __': app = QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec_()) 在上面的代码中,我们重写了QWidget的 close Event ()方法,并在关闭窗口之前打印了一条消息。最后,我们 调用 event .accept()方法来关闭窗口。