【问题标题】:How to properly quit a QThread in PyQt5 when using moveToThread使用 moveToThread 时如何在 PyQt5 中正确退出 QThread
【发布时间】:2017-01-28 06:22:06
【问题描述】:

我试图在完成处理后退出一个线程。我正在使用 moveToThread。我试图通过在插槽中调用 self.thread.quit() 来从主线程中退出工作线程。那是行不通的。

我发现了几个使用 moveToThread 启动线程的示例,例如这个。但我找不到如何退出。

from PyQt5.QtCore import QObject, QThread
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        print("Base init")
        self.start_thread()

    @pyqtSlot(int)
    def onFinished(self, i):
        print("Base caught finished, {}".format(i))
        self.thread.quit()
        print('Tried to quit thread, is the thread still running?')
        print(self.thread.isRunning())

    def start_thread(self):
        self.thread = QThread()
        self.w = Worker()
        self.w.finished1[int].connect(self.onFinished)
        self.w.moveToThread(self.thread)
        self.thread.started.connect(self.w.work)
        self.thread.start()

class Worker(QObject):
    finished1 = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        print("Worker init")

    def work(self):
        print("Worker work")
        self.finished1.emit(42)


if __name__ == "__main__":
    import sys
    from PyQt5.QtWidgets import QApplication

    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()

sys.exit(app.exec_())

这是我所有打印功能的输出(当然没有颜色):

Base init
Worker init
Worker work
Base caught finished, 42
Tried to quit thread, is the thread still running?
True

【问题讨论】:

    标签: multithreading python-3.x pyqt pyqt5 qthread


    【解决方案1】:

    尝试多次运行您的脚本。调用self.thread.isRunning() 的结果总是一样吗?在检查线程是否仍在运行之前尝试添加对time.sleep(1) 的调用。注意到有什么不同吗?

    请记住,您正在从程序的主线程调用另一个线程,根据定义,该线程是异步的。在执行下一条指令之前,您的程序不会等待确保 self.thread.quit() 已完成。

    【讨论】:

    • 谢谢!你说的对。线程毕竟退出了。 print(self.thread.isRunning()) 添加time.sleep(1)后显示为False
    猜你喜欢
    • 2013-12-17
    • 2013-10-15
    • 2018-12-11
    • 2021-06-11
    • 2019-04-02
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多