在PyQt5中使用moveToThread时,正确退出moveToThread的方法如下:
from PyQt5.QtCore import QObject, QThread, pyqtSignal
class Worker(QObject):
finished = pyqtSignal()
def __init__(self):
super().__init__()
def do_work(self):
# 执行耗时操作
# ...
# 完成工作后发射finished信号
self.finished.emit()
from PyQt5.QtCore import QThread
# 创建Worker对象
worker = Worker()
# 创建QThread对象
thread = QThread()
# 将Worker对象移动到QThread线程中
worker.moveToThread(thread)
worker.finished.connect(thread.quit)
thread.started.connect(worker.do_work)
thread.start()
thread.quit()
thread.wait()
完整示例代码如下:
from PyQt5.QtCore import QObject, QThread, pyqtSignal
class Worker(QObject):
finished = pyqtSignal()
def __init__(self):
super().__init__()
def do_work(self):
# 执行耗时操作
# ...
# 完成工作后发射finished信号
self.finished.emit()
# 创建Worker对象
worker = Worker()
# 创建QThread对象
thread = QThread()
# 将Worker对象移动到QThread线程中
worker.moveToThread(thread)
# 连接Worker对象的finished信号到QThread的quit槽函数
worker.finished.connect(thread.quit)
# 连接QThread的started信号到Worker对象的do_work槽函数
thread.started.connect(worker.do_work)
# 启动线程
thread.start()
# 在需要退出线程的地方调用thread.quit()函数
thread.quit()
# 等待线程退出
thread.wait()
这样,在使用moveToThread时,可以正确退出moveToThread,并且保证线程的正常执行。
领取专属 10元无门槛券
手把手带您无忧上云