1 线程(QThread)


1.1 基本写法

线程 — QThread
python from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton from PyQt6.QtCore import QThread, pyqtSignal, QObject import sys, time class SubThread(QThread): # 创建线程信号,并将线程接入信号的数据类型 trigger = pyqtSignal(str) # 实例化类时触发时执行的任务 def __init__(self): # 继承父级类属性 super().__init__() # 销毁类时触发时执行的任务 def __del__(self): # 停止线程 self.wait() # 启动线程时执行的任务 def run(self): # 线程传向外传递信号 self.trigger.emit('子线程开始') # 线程休眠 8s self.sleep(8) # 也可以使用解释器自带的 time 模块实现:time.sleep(8) self.trigger.emit('子线程结束') def callback(str): print(str) class QWindow(QMainWindow): def __init__(self): super().__init__() self.Init_UI() def Init_UI(self): btn = QPushButton('歪日') btn.clicked.connect(self.btnclicked) # 创建线程对象 self.subthread = SubThread() # 线程启动后信号传递 self.subthread.trigger.connect(callback) self.setCentralWidget(btn) self.show() def btnclicked(self): self.btn.setEnabled(False) # 启动线程 self.subthread.start() if __name__ == '__main__': app = QApplication(sys.argv) ex = QWindow() app.exit(app.exec())
DLC
[QThread Class Qt Core 6.3.2](https://doc.qt.io/qt-6/qthread.html)

1.2 传参

  • 通过线程类实例方法传参赋值,可一次传多个参数;
线程 — QThread
python from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton from PyQt6.QtCore import QThread, pyqtSignal, QObject import sys, time class SubThread(QThread): trigger = pyqtSignal(str) # 注意必要时可能会增加传参的数据类型 def __init__(self): super().__init__() def __del__(self): self.wait() def inputstr(self,str1,str2): self.str1 = str1 self.str2 = str2 def run(self): self.trigger.emit(self.str1 + '子线程开始' + self.str2) self.sleep(8) self.trigger.emit(self.str1 + '子线程结束' + self.str2) def callback(str): print(str) class QWindow(QMainWindow): def __init__(self): super().__init__() self.Init_UI() def Init_UI(self): self.btn = QPushButton('歪日') self.btn.clicked.connect(self.btnclicked) self.subthread = SubThread() self.subthread.trigger.connect(callback) self.subthread.inputstr('我去了,','啦!!!') self.setCentralWidget(self.btn) self.show() def btnclicked(self): self.btn.setEnabled(False) # 启动线程 self.subthread.start() if __name__ == '__main__': app = QApplication(sys.argv) ex = QWindow() app.exit(app.exec())