PySide / PyQt detect if user trying to close window

If you just have one window (i.e the last window) you want to detect then you can use the setQuitOnLastWindowClosed static function and the lastWindowClosed signal.

from PySide2 import QtGui
import sys


def keep_alive():
    print("ah..ah..ah..ah...staying alive...staying alive")
    window.setVisibility(QtGui.QWindow.Minimized)


if __name__ == '__main__':
    app = QtGui.QGuiApplication()
    app.setQuitOnLastWindowClosed(False)
    app.lastWindowClosed.connect(keep_alive)

    window = QtGui.QWindow()
    window.show()

    sys.exit(app.exec_())

Hope that helps someone, it worked for me as on my first attempt I couldn't override closeEvent(), lack of experience!


Override the closeEvent method of QWidget in your main window.

For example:

class MainWindow(QWidget): # or QMainWindow
    ...

    def closeEvent(self, event):
        # do stuff
        if can_exit:
            event.accept() # let the window close
        else:
            event.ignore()

Another possibility is to use the QApplication's aboutToQuit signal like this:

app = QApplication(sys.argv)
app.aboutToQuit.connect(myExitHandler) # myExitHandler is a callable