PyQt5.QThread 的 start() 方法不执行 运行() 方法

PyQt5.QThread's start() méthod don't execute the run() méthod

我开始学习 PyQt5 和 Qthread,我正在尝试做一个简单的 QThread 实现,我知道这很明显,但我真的不明白为什么它不起作用

我的代码:

from PyQt5 import QtCore


class WorkingThread(QtCore.QThread):
    def __init__(self):
        super().__init__()

    def run(self):
        print(" work !")


class MainWindow(QtCore.QObject):

    worker_thread = WorkingThread()

    def engage(self):
        print("calling start")
        self.worker_thread.start()


if __name__ == "__main__":
    main = MainWindow()
    main.engage()

输出:

呼叫开始

进程已完成,退出代码为 0

没有"work !"打印

Qt 的许多元素需要事件循环才能正常工作,QThread 就是这种情况,因为在这种情况下没有 GUI,因此创建 QCoreApplication 是合适的:

from PyQt5 import QtCore


class WorkingThread(QtCore.QThread):
    def run(self):
        print(" work !")


class MainWindow(QtCore.QObject):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.worker_thread = WorkingThread()

    def engage(self):
        print("calling start")
        self.worker_thread.start()


if __name__ == "__main__":
    import sys

    app = QtCore.QCoreApplication(sys.argv)
    main = MainWindow()
    main.engage()
    sys.exit(app.exec_())