我开始学习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结束的过程
没有“工作!”打印
答案 0 :(得分:0)
Qt的许多元素都需要一个eventloop才能正常工作,而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_())