使用pyside6实现一个简单的线程池连接,需要两个不同按钮并行处理两个不同的任务,可以尝试让他们在QListWidget中添加item,并带有ui窗口展示
时间: 2023-05-11 10:02:03 浏览: 124
好的,这是一个编程类的问题,我可以回答。以下是使用 PySide6 实现一个简单的线程池连接的代码:
```python
import sys
import time
from PySide6.QtCore import Qt, QThreadPool, QRunnable, QObject, Signal
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QListWidget, QLabel
class WorkerSignals(QObject):
finished = Signal()
result = Signal(str)
class Worker(QRunnable):
def __init__(self, task, *args, **kwargs):
super().__init__()
self.task = task
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
def run(self):
result = self.task(*self.args, **self.kwargs)
self.signals.result.emit(result)
self.signals.finished.emit()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("线程池连接示例")
self.resize(400, 300)
self.threadpool = QThreadPool()
self.list_widget = QListWidget()
self.label = QLabel("任务结果:")
self.button1 = QPushButton("任务1")
self.button1.clicked.connect(self.start_task1)
self.button2 = QPushButton("任务2")
self.button2.clicked.connect(self.start_task2)
button_layout = QHBoxLayout()
button_layout.addWidget(self.button1)
button_layout.addWidget(self.button2)
main_layout = QVBoxLayout()
main_layout.addWidget(self.list_widget)
main_layout.addLayout(button_layout)
main_layout.addWidget(self.label)
central_widget = QWidget()
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def start_task1(self):
task = self.task1
worker = Worker(task)
worker.signals.result.connect(self.add_item)
self.threadpool.start(worker)
def start_task2(self):
task = self.task2
worker = Worker(task)
worker.signals.result.connect(self.show_result)
self.threadpool.start(worker)
def task1(self):
time.sleep(5)
return "任务1完成"
def task2(self):
time.sleep(3)
return "任务2完成"
def add_item(self, item):
self.list_widget.addItem(item)
def show_result(self, result):
self.label.setText("任务结果:" + result)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
```
这个程序创建了一个主窗口,包含一个 QListWidget 和两个 QPushButton。当点击按钮时,程序会启动一个线程来执行相应的任务,并将任务结果添加到 QListWidget 中或者在 QLabel 中显示。这个程序使用了 PySide6 的 QThreadPool 和 QRunnable 类来实现线程池连接。
阅读全文