Python PyQt5——QThread使用方法与代码实践
import sys
from PyQt5.QtCore import QThread, QObject, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
# 定义一个继承自QObject的子类,用于在QThread中实现需要的功能
class WorkerSignals(QObject):
finished = pyqtSignal(str)
class Worker(QRunnable):
def __init__(self, data):
super(Worker, self).__init__()
self.data = data
self.signals = WorkerSignals()
def run(self):
# 这里可以执行耗时的任务
# 这里仅示例打印数据和结束信号
print('Running on thread: %s' % self.data)
self.signals.finished.emit('Worker finished')
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.button = QPushButton('Start', self)
self.button.clicked.connect(self.on_start)
def on_start(self):
worker = Worker('test')
worker.signals.finished.connect(self.on_finished)
thread = QThread(self)
worker.moveToThread(thread)
thread.started.connect(worker.run)
thread.finished.connect(self.on_thread_finished)
thread.start()
def on_finished(self, s):
print(s)
def on_thread_finished(self):
print('Thread finished')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
这段代码定义了一个QThread的使用方法,在MainWindow的on\_start方法中创建了一个Worker对象,并将其放到一个新的QThread中执行。Worker的run方法被连接到了QThread的started信号,以便在新线程中执行。当run方法结束后,QThread的finished信号会被触发,并调用on\_thread\_finished方法。这个例子展示了如何在PyQt5中使用QThread来执行后台任务,并在任务完成时更新UI。
评论已关闭