在不冻结 PyQt GUI 的情况下跟踪 Python 中的线程进度,可以使用 QThread 和信号(Signals)来实现。以下是一个简单的示例:
首先,导入所需的库:
from PyQt5.QtCore import QObject, pyqtSignal, QThread
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
接下来,创建一个工作线程类,该类继承自 QObject,并定义一个信号用于发送进度信息:
class WorkerThread(QObject):
progress = pyqtSignal(int)
def run(self):
for i in range(101):
self.progress.emit(i)
# 模拟耗时操作
time.sleep(0.1)
然后,创建一个 PyQt 应用程序和主窗口:
app = QApplication([])
window = QMainWindow()
在主窗口中添加一个按钮和一个用于显示进度的小部件:
start_button = QPushButton("开始")
progress_widget = QWidget()
layout = QVBoxLayout()
layout.addWidget(start_button)
layout.addWidget(progress_widget)
window.setLayout(layout)
创建一个 QThread 实例,并将工作线程对象移动到该线程中:
thread = QThread()
worker = WorkerThread()
worker.moveToThread(thread)
接下来,将线程的信号与主窗口的槽(Slot)连接起来,以便在线程发送进度信息时更新 GUI:
worker.progress.connect(progress_widget.setValue)
最后,启动线程:
thread.start()
完整代码如下:
import sys
import time
from PyQt5.QtCore import QObject, pyqtSignal, QThread
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
class WorkerThread(QObject):
progress = pyqtSignal(int)
def run(self):
for i in range(101):
self.progress.emit(i)
time.sleep(0.1)
app = QApplication([])
window = QMainWindow()
start_button = QPushButton("开始")
progress_widget = QWidget()
layout = QVBoxLayout()
layout.addWidget(start_button)
layout.addWidget(progress_widget)
window.setLayout(layout)
thread = QThread()
worker = WorkerThread()
worker.moveToThread(thread)
worker.progress.connect(progress_widget.setValue)
thread.start()
window.show()
sys.exit(app.exec_())
这个示例将在不冻结 PyQt GUI 的情况下跟踪 Python 中的线程进度。
领取专属 10元无门槛券
手把手带您无忧上云