PySide / PyQt detect if user trying to close window

Question:

is there a way to detect if user trying to close window?
For example, in Tkinter we can do something like this:

def exit_dialog():
    #do stuff
    pass

root = Tk()
root.protocol("WM_DELETE_WINDOW", exit_dialog)
root.mainloop()

Thanks.

Asked By: SaulTigh

||

Answers:

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
Answered By: Oleh Prypin

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!

Answered By: mcdixon
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.