PyQt QProgressDialog not reponding

272 views Asked by At

I am new in programming in PyQt (python interface), I like to use QProgressDialog, to show the progress of some tasks, so, the problem is, I had this:

enter image description here

while the change the value of progress , thank you for the help

def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(800, 600)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.label = QtWidgets.QLabel(self.centralwidget)
    self.label.setGeometry(QtCore.QRect(250, 160, 231, 161))
    self.label.setObjectName("label")
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.p = QProgressDialog('titel','',0,10000)
    self.p.setValue(0)
    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.label.setText(_translate("label test"))
def work(self):
    for index in range(10001):
       time.sleep(2)
       self.p.setValue(index)
       print(index)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.work()
    sys.exit(app.exec_())
1

There are 1 answers

2
eyllanesc On

PyQt creates a loop through app.exec_(), and this serves to manage the GUI dynamics such as signals, events, etc. So if you interrupt that cycle you would have problems like the one shown. And in its case sleep() blocks the execution of the program. One way to solve this problem is using a QTimer as shown below:

[...]
    self.p = QProgressDialog('title','',0,10000)
    self.p.setValue(0)
    self.timer = QtCore.QTimer(MainWindow)
    self.timer.timeout.connect(self.work)
    self.timer.start(2000)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
[...]
def work(self):
    self.p.setValue(self.p.value()+1)
    if self.p.value() == self.p.maximum():
        self.timer.stop()
[...]