子线程创建和结束的完整代码
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import time
# 该 Worker 类实现了乘法运算
class Worker(QObject):
# 定义一个信号
on_result = pyqtSignal(float)
def __init__(self, a, b):
super().__init__()
self.a = a
self.b = b
def run(self):
print("开始处理(预计2秒)")
# 模拟原本会导致UI阻塞的阻塞语句
time.sleep(8)
result = self.a * self.b
# 发射信号
self.on_result.emit(result)
class Window(QWidget):
def __init__(self):
super().__init__()
l = QVBoxLayout(self)
button = QPushButton("run")
button.clicked.connect(self.on_button_clicked)
l.addWidget(button)
def on_button_clicked(self):
# 创建 Worker 对象
self.worker = Worker(7, 8)
# 创建线程
thread = QThread(self)
self.worker.moveToThread(thread)
self.worker.on_result.connect(self.on_worker_done)
# 线程完成后退出
self.worker.on_result.connect(lambda: thread.quit())
# 启动线程
thread.started.connect(self.worker.run)
thread.start()
def on_worker_done(self, value: float):
print("我得到啦!", value)
if __name__ == "__main__":
app = QApplication([])
w = Window()
w.show()
app.exec_()
关键字: