pyqt5 线程池 更新ui
时间: 2023-09-08 22:01:17 浏览: 50
在PyQt5中使用线程池来更新UI是一种常见的做法,它可以避免在主线程中执行耗时操作造成界面卡顿的问题。以下是使用线程池更新UI的示例代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThreadPool, QObject, QTimer
from datetime import datetime
import time
class Worker(QObject):
def __init__(self, num, callback):
super().__init__()
self.num = num
self.callback = callback
def run(self):
# 模拟耗时操作
time.sleep(2)
result = self.num * self.num
# 将结果通过回调函数发送给主线程更新UI
self.callback.emit(result)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.threadpool = QThreadPool()
self.setWindowTitle("线程池更新UI示例")
self.resize(300, 200)
self.label = QLabel("等待结果...", self)
self.label.move(100, 50)
self.label.resize(150, 30)
self.label.setAlignment(Qt.Qt.AlignCenter)
self.start_button = QPushButton("开始计算", self)
self.start_button.move(100, 100)
self.start_button.clicked.connect(self.start_calculation)
def start_calculation(self):
# 创建一个Worker对象,并将其移入线程池
worker = Worker(10, self.update_ui)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def update_ui(self, result):
# 在主线程中更新UI
self.label.setText(str(result))
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
```
在此示例中,使用了`QThreadPool`类来创建线程池,并将`Worker`对象添加到线程池中。`Worker`类继承自`QObject`,负责执行耗时操作,并通过回调函数`callback`来发送结果给主线程。
点击"开始计算"按钮后,会创建一个新的`Worker`对象并将其移入线程池,然后线程池会自主调度一个可用线程来执行`run`方法中的耗时操作。在操作完成后,会调用回调函数`update_ui`来更新UI界面。
在`update_ui`函数中,通过`setText`方法将计算结果显示在`QLabel`控件上,从而实现了在PyQt5中使用线程池来更新UI的功能。