pyqt updating progress bar using thread

孤者浪人 提交于 2020-05-09 12:07:10

问题


I want to update the progress bar from my main.py using thread approach.

if __name__ == "__main__":

       app = QApplication(sys.argv)
       uiplot = gui.Ui_MainWindow()

       Update_Progressbar_thread = QThread() 
       Update_Progressbar_thread.started.connect(Update_Progressbar)


       def Update_Progressbar():
              progressbar_value = progressbar_value + 1
              while (progressbar_value < 100):
                     uiplot.PSprogressbar.setValue(progressbar_value)
                     time.sleep(0.1)
      uiplot.PSStart_btn.clicked.connect(Update_Progressbar_thread.start) 

The problem is this approach james my GUI and I cannot click any buttons etc.

Alternatively how can I make it work ? Thanks


回答1:


Explanation:

With your logic you are invoking "Update_Progressbar" to run when the QThread starts, but where will "Update_Progressbar" run? Well, in the main thread blocking the GUI.

Solution:

Your goal is not to run "Update_Progressbar" when the QThread starts but to run in the thread that handles QThread. So in this case you can create a Worker that lives in the thread handled by QThread

class Worker(QObject):
    progressChanged = pyqtSignal(int)

    def work(self):
        progressbar_value = 0
        while progressbar_value < 100:
            self.progressChanged.emit(progressbar_value)
            time.sleep(0.1)


if __name__ == "__main__":

    app = QApplication(sys.argv)
    uiplot = gui.Ui_MainWindow()

    thread = QThread()
    thread.start()

    worker = Worker()
    worker.moveToThread(thread)
    worker.progressChanged.connect(uiplot.PSprogressbar.setValue)
    uiplot.PSStart_btn.clicked.connect(worker.work)

    # ...


来源:https://stackoverflow.com/questions/61639843/pyside2-progressbar-displaying-file-conversion-stutus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!