pythonPYQT5绑定窗口开启多线程
时间: 2024-09-29 14:00:32 浏览: 64
在Python中,结合PyQt5创建图形用户界面时,如果你想要在一个窗口中开启多线程处理耗时任务,可以使用QThread或者ThreadPoolExecutor。以下是基本步骤:
1. 导入所需模块:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton
from PyQt5.QtCore import Qt, pyqtSlot, QRunnable, QObject, QThreadPool
```
2. 创建一个单独的线程类,继承自QObject或QThread:
```python
class WorkerThread(QRunnable):
def __init__(self, function, *args, **kwargs):
super().__init__()
self.function = function
self.args = args
self.kwargs = kwargs
@pyqtSlot()
def run(self):
self.function(*self.args, **self.kwargs)
```
3. 在窗口类里设置线程池并启动工作线程:
```python
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# 创建线程池
self.pool = QThreadPool()
# 添加按钮并连接槽函数
button = QPushButton('Start Task', self)
button.clicked.connect(self.start_thread)
layout = QVBoxLayout()
layout.addWidget(button)
self.setLayout(layout)
@pyqtSlot()
def start_thread(self):
worker = WorkerThread(self.long_running_task)
self.pool.start(worker) # 启动新线程
def long_running_task(self):
# 这里编写你的长时间运行的任务
# ...
print("Task running in a separate thread...")
```
在这个例子中,点击按钮后,`long_running_task`会在独立的线程中执行,不会阻塞主线程,让你的GUI保持响应。
阅读全文