使用pyside6实现一个简单的线程池连接,需要并行处理两个不同的任务,并带有ui窗口展示
时间: 2023-05-11 17:02:02 浏览: 177
可以使用QThreadPool类来实现一个简单的线程池连接,同时使用QRunnable类来定义任务。以下是一个示例代码:
```python
from PySide6.QtCore import QObject, QRunnable, QThreadPool, Signal
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton
import time
class Task1(QRunnable):
def __init__(self):
super().__init__()
def run(self):
print("Task1 started")
time.sleep(5)
print("Task1 finished")
class Task2(QRunnable):
def __init__(self):
super().__init__()
def run(self):
print("Task2 started")
time.sleep(3)
print("Task2 finished")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.threadpool = QThreadPool()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout()
self.central_widget.setLayout(self.layout)
self.label = QLabel("Click the button to start tasks")
self.layout.addWidget(self.label)
self.button = QPushButton("Start tasks")
self.button.clicked.connect(self.start_tasks)
self.layout.addWidget(self.button)
def start_tasks(self):
self.label.setText("Tasks started")
task1 = Task1()
task2 = Task2()
self.threadpool.start(task1)
self.threadpool.start(task2)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
在这个示例中,我们定义了两个任务类Task1和Task2,它们分别模拟了两个不同的任务。我们还定义了一个MainWindow类,它包含一个按钮和一个标签,用于启动任务和显示任务状态。
在start_tasks方法中,我们创建了两个任务实例,并使用QThreadPool类的start方法将它们提交到线程池中。线程池会自动分配线程来执行这些任务。
注意,这个示例中没有使用UI窗口来展示任务状态,但你可以在任务类中添加信号来更新UI。