7

Here's an example below:

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
    print "you just closed the pyqt window!!! you are awesome!!!"

The print statement above doesn't seem to get executed while the window is open or after I close the window. I want it to print after I close the window.

user1251007
  • 15,891
  • 14
  • 50
  • 76
Crawdad_Buckwheat
  • 313
  • 1
  • 4
  • 16

3 Answers3

13

I do that by redefining the closeEvent method, like this:

class YourMainWindow(QtGui.QMainWindow):

    (...)

    def closeEvent(self, *args, **kwargs):
        super(QtGui.QMainWindow, self).closeEvent(*args, **kwargs)
        print "you just closed the pyqt window!!! you are awesome!!!"

I hope that helps

Federico Barabas
  • 659
  • 8
  • 21
  • I think this is close to what I need. It looks like you are calling closeEvent inside the definition of closeEvent. I must not understand what is going on here. Can you direct me to more examples using super and closeEvent? – Crawdad_Buckwheat Jul 29 '14 at 23:59
  • That's exactly what I'm doing. I redefine `closeEvent` to include your print statement but I also include the original `closeEvent` because I don't want to miss the things it does originally. Documentation: https://docs.python.org/2/library/functions.html#super Nice explanation here: http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods – Federico Barabas Jul 30 '14 at 03:10
  • Thanks for the help. I will check out those links. – Crawdad_Buckwheat Jul 31 '14 at 15:29
  • I tried your solution above and it worked. The key is to create a subclass of the QtGui.QMainWindow and edit its closeEvent function so that it also executes the print statement (or, in my case, other code ;) ) after the window is closed. Thanks again, I also learned about subclasses today! – Crawdad_Buckwheat Jul 31 '14 at 23:53
2

Usually most PyQt applications have such lines in main:

app = QApplication(sys.argv)
myclass = MyClass()
myclass.show()
sys.exit(app.exec_())

What you can do is define a function that does all the above, and then do whatever you want after the call to app.exec_():

def appExec():
  app = QApplication(sys.argv)
  # and so on until we reach:
  app.exec_()
  print("my message...")
  # other work...

All what you would have in main is:

sys.exit(appExec())
alothman
  • 54
  • 3
1

The following works correctly for me (the final print statement is executed):

from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.show()
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
    print "you just closed the pyqt window!!! you are awesome!!!"
Luke
  • 11,374
  • 2
  • 48
  • 61