Prompt on exit in PyQt application

34,326

Yes. You need to override the default close behaviour of the QWidget representing your application so that it doesn't immediately accept the event. The basic structure you want is something like this:

def closeEvent(self, event):

    quit_msg = "Are you sure you want to exit the program?"
    reply = QtGui.QMessageBox.question(self, 'Message', 
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

    if reply == QtGui.QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()

The PyQt tutorial mentioned by las3rjock has a nice discussion of this. Also check out the links from the PyQt page at Python.org, in particular the official reference, to learn more about events and how to handle them.

Share:
34,326
Kirill Titov
Author by

Kirill Titov

Good bye. Have fun with community driven moderation.

Updated on July 09, 2022

Comments

  • Kirill Titov
    Kirill Titov almost 2 years

    Is there any way to promt user to exit the gui-program written in Python?

    Something like "Are you sure you want to exit the program?"

    I'm using PyQt.