我使用PyQt5写GUI程序,老是出现“未响应”的情况,将耗时操作放入到子线程去运行也是如此,我写了下面一个小程序来测试,发现这些任务的确是在主线程执行的,各位大神来求解释?我的代码如下:
from PyQt5.QtCore import QThread, QObject, QCoreApplication, qDebug, QTimer
class Worker(QObject):
def on_timeout(self):
qDebug('Worker.on_timeout get called from: %s' % hex(int(QThread.currentThreadId())))
if __name__ == '__main__':
import sys
app = QCoreApplication(sys.argv)
qDebug('From main thread: %s' % hex(int(QThread.currentThreadId())))
t = QThread()
worker = Worker()
timer = QTimer()
timer.timeout.connect(worker.on_timeout)
timer.start(1000)
timer.moveToThread(t)
worker.moveToThread(t)
t.start()
app.exec_()
Windows下的输出是:
From main thread: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
Worker.on_timeout get called from: 0x7f4
这样写