How to handle window close event in PyQt5?

In PyQt5, you can use the closeEvent method to handle window closing events. This method is called when the window is closed, allowing us to override it and implement custom closing behavior.

The following is a simple example code that demonstrates how to show a confirmation dialog when closing a window.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', '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(sys.argv)
    widget = MyWidget()
    widget.show()
    sys.exit(app.exec_())

In the code above, we defined a custom window class MyWidget that inherits from QWidget and overridden the closeEvent method. In this method, we displayed a confirmation dialog to ask the user if they are sure they want to close the window. Depending on the user’s choice, we can call event.accept() to accept the close event, or event.ignore() to disregard the close event.

By overriding the closeEvent method, we can achieve various customized closing behaviors, such as displaying warning messages, saving data, etc.

Leave a Reply 0

Your email address will not be published. Required fields are marked *