简体   繁体   中英

Pyqt Terminal hangs after excuting close window command

I have read lots of threads online, but still I could not find the solution. My question should be very simple: how to close a Pyqt window WITHOUT clicking a button or using a timer. The code I tried is pasted below

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_())

My Pyqt GUI is designed using Qt designer, and it is nothing but a progress bar that keeps moving from left to right (busy indication).

However, when I run the code above, the terminal still hangs after the Pyqt window is closed. Ctrl+C also couldn't kill the process. In short, how can I properly close/terminate a Pyqt window without clicking a button or using a timer?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM