【问题标题】:PyQt5.QThread's start() méthod don't execute the run() méthodPyQt5.QThread 的 start() 方法不执行 run() 方法
【发布时间】:2018-08-06 22:48:35
【问题描述】:

我开始学习 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 结束

没有“工作!”打印出来的

【问题讨论】:

    标签: python pyqt pyqt5 qthread


    【解决方案1】:

    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_())
    

    【讨论】:

    • 非常感谢!我已经为此绞尽脑汁
    最近更新 更多