关闭PyQt窗口后如何执行更多代码?

时间:2014-07-28 23:07:27

标签: python pyqt

以下是一个例子:

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!!!"

当窗口打开或关闭窗口后,上面的print语句似乎没有执行。我想在关闭窗口后进行打印。

3 个答案:

答案 0 :(得分:8)

我通过重新定义closeEvent方法来做到这一点,如下所示:

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!!!"

我希望有帮助

答案 1 :(得分:1)

以下对我来说正常工作(执行最终的print语句):

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!!!"

答案 2 :(得分:1)

通常大多数PyQt应用程序在main中都有这样的行:

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

你可以做的是定义一个完成上述所有功能的函数,然后在调用app.exec _()后执行任何操作:

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

你所拥有的主要内容是:

sys.exit(appExec())