在关闭窗口命令后,Pyqt终端挂起

时间:2016-08-31 13:33:36

标签: python pyqt pyqt4

我在线阅读了很多帖子,但我找不到解决方案。我的问题应该很简单:如何在不单击按钮或使用计时器的情况下关闭Pyqt窗口。 我试过的代码粘贴在

下面
from PyQt4 import QtGui, QtCore
import numpy as np
import progressMeter_simple
import sys
import time
import pdb
class ProgressMeter(progressMeter_simple.Ui_Dialog, QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        progressMeter_simple.Ui_Dialog.__init__(self)
        self.setupUi(self)
        self.progressBar.setRange(0, 0)
        QtGui.QApplication.processEvents()
    def termination(self):
        time.sleep(5)
        self.close()
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    Dialog = ProgressMeter()
    Dialog.show()
    Dialog.termination()
    sys.exit(app.exec_())

我的Pyqt GUI是使用Qt设计器设计的,它只是一个从左到右移动的进度条(忙碌指示)。

但是,当我运行上面的代码时,终端仍然在Pyqt窗口关闭后挂起。 Ctrl + C也无法终止进程。 简而言之,如何在不单击按钮或使用计时器的情况下正确关闭/终止Pyqt窗口?

1 个答案:

答案 0 :(得分:0)

It's not working because you're calling GUI methods on the dialog (close()) outside of the event loop. The event loop doesn't start until you call app.exec_().

If you really want to close the dialog immediately after it opens without using a QTimer, you can override the showEvent() method and call termination() from there, which gets called when the dialog is first displayed.

class ProgressMeter(progressMeter_simple.Ui_Dialog, QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        progressMeter_simple.Ui_Dialog.__init__(self)
        self.setupUi(self)
        self.progressBar.setRange(0, 0)

    def showEvent(self, event):
        super(ProgressMeter, self).showEvent(event)
        self.termination()