使用pyside2实现带signal的线程池
时间: 2023-05-17 12:04:17 浏览: 272
可以使用QThreadPool类来实现带signal的线程池,具体实现可以参考以下代码:
```python
from PySide2.QtCore import QObject, QRunnable, QThreadPool, Signal
class WorkerSignals(QObject):
finished = Signal()
result = Signal(object)
class Worker(QRunnable):
def __init__(self, func, *args, **kwargs):
super(Worker, self).__init__()
self.func = func
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
def run(self):
result = self.func(*self.args, **self.kwargs)
self.signals.result.emit(result)
self.signals.finished.emit()
def my_func():
# do some work here
return "result"
pool = QThreadPool()
worker = Worker(my_func)
worker.signals.result.connect(print)
pool.start(worker)
```
这段代码实现了一个带signal的线程池,其中Worker类继承自QRunnable,可以在run方法中执行需要在子线程中执行的任务。WorkerSignals类定义了两个signal,分别是finished和result,用于在任务完成时发射信号。在主线程中,可以通过连接result信号来获取任务的结果。
阅读全文