from PyQt4.QtGui import QApplication, QMainWindow, QMessageBox from PyQt4.QtCore import QObject, pyqtSignal, QCoreApplication, QEvent class MainWindow(QMainWindow): def closeEvent(self, event): reply = QMessageBox.question(self, 'Confirm Exit', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() if __name__ == '__main__': app = QApplication([]) window = MainWindow() window.show() app.exec_()
from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, QPushButton, QMessageBox from PyQt4.QtCore import QObject, pyqtSignal, QCoreApplication, QEvent class Widget(QWidget): closed = pyqtSignal() def __init__(self, parent=None): super(Widget, self).__init__(parent) layout = QVBoxLayout() button = QPushButton("Close Widget") button.clicked.connect(self.close) layout.addWidget(button) self.setLayout(layout) def closeEvent(self, event): self.closed.emit() if __name__ == '__main__': app = QApplication([]) widget = Widget() widget.closed.connect(lambda: QMessageBox.information(None, "Message", "Widget Closed")) widget.show() app.exec_()In this example, we create a custom QWidget named Widget. Inside the widget, we create a QPushButton that when clicked calls the close() method of the Widget. We also override the closeEvent method of the Widget to emit a pyqtSignal named closed when the widget is closed. We then create an instance of the Widget and connect the closed signal to a lambda function that displays a QMessageBox with a message when the widget is closed. Overall, these examples demonstrate how to use the QCloseEvent class provided by PyQt4 to handle close events of a widget, and how to emit a signal when a widget is closed.