pyqt5进度条更新,多线程
from PyQt5.QtCore import QThread, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class WorkerThread(QThread):
progressUpdated = pyqtSignal(int)
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
def run(self):
for i in range(101):
self.progressUpdated.emit(i)
self.msleep(100) # 模拟耗时操作
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.label = QLabel("Progress: 0%")
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.setLayout(self.layout)
self.workerThread = WorkerThread()
self.workerThread.progressUpdated.connect(self.updateProgress)
self.timer = QTimer()
self.timer.timeout.connect(self.startCalculation)
self.timer.start(1000) # 每秒触发一次计算
def startCalculation(self):
if not self.workerThread.isRunning():
self.workerThread.start()
def updateProgress(self, progress):
self.label.setText(f"Progress: {progress}%")
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
这段代码使用了PyQt5库创建了一个简单的窗口应用程序,其中包含一个标签用于显示进度信息。在后台使用QThread
类创建了一个工作线程,模拟耗时操作,并通过信号progressUpdated
将进度更新发送给主线程。
主要的类和功能如下:
WorkerThread
类是一个自定义的线程类,继承自QThread
。在run()
方法中,它通过循环从0到100依次发送进度更新信号progressUpdated
。MainWindow
类是主窗口类,继承自QWidget
。在__init__()
方法中,创建了一个标签label
并设置布局,然后创建了一个WorkerThread
实例workerThread
。连接了progressUpdated
信号与updateProgress
槽函数,在接收到进度更新时更新标签内容。另外,还创建了一个定时器timer
,每秒触发一次startCalculation
函数,用于启动工作线程。- 在
startCalculation
函数中,检查工作线程是否正在运行,如果没有则启动它。 updateProgress
函数用于更新标签的文本,显示当前进度。
最后,在if __name__ == "__main__"
条件下创建一个QApplication
实例,创建主窗口并显示应用程序。
该应用程序会显示一个窗口,其中的标签会每秒更新一次进度信息,直到达到100%为止。这个例子展示了使用QThread
和信号槽机制在PyQt5中实现多线程的简单应用场景,以及如何在主线程中更新用户界面。