PySide / PyQt detect if user trying to close window

SaulTigh picture SaulTigh · Feb 12, 2012 · Viewed 47.4k times · Source

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.

Answer

Oleh Prypin picture Oleh Prypin · Feb 12, 2012

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