PySide / PyQt detect if user trying to close window

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x