pyqt使用线程更新进度条 [英] pyqt updating progress bar using thread
问题描述
我想使用线程方法从我的 main.py 更新进度条.
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)
问题是这种方法干扰了我的 GUI,我无法点击任何按钮等.
The problem is this approach james my GUI and I cannot click any buttons etc.
或者我怎样才能让它工作?谢谢
Alternatively how can I make it work ? Thanks
推荐答案
说明:
根据您的逻辑,您将在 QThread 启动时调用Update_Progressbar"来运行,但是Update_Progressbar"将在哪里运行?好吧,在阻塞 GUI 的主线程中.
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.
解决方案:
您的目标不是在 QThread 启动时运行Update_Progressbar",而是在处理 QThread 的线程中运行.因此,在这种情况下,您可以创建一个驻留在 QThread 处理的线程中的 Worker
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)
# ...
这篇关于pyqt使用线程更新进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!