Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute more code after closing a PyQt window?

Tags:

python

pyqt

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.

like image 620
Crawdad_Buckwheat Avatar asked Jul 28 '14 23:07

Crawdad_Buckwheat


3 Answers

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

like image 55
Federico Barabas Avatar answered Oct 27 '22 01:10

Federico Barabas


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!!!"
like image 41
Luke Avatar answered Oct 27 '22 01:10

Luke


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())
like image 38
alothman Avatar answered Oct 27 '22 03:10

alothman