PyQt5 多线程 子线程的任务怎么跑到主线程去运行了?

我使用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
阅读 9.8k
1 个回答

这样写

from PyQt5.QtCore import QThread ,  pyqtSignal,  QDateTime , QObject
from PyQt5.QtWidgets import QApplication,  QDialog,  QLineEdit
import time
import sys

class BackendThread(QObject):
    # 通过类成员对象定义信号
    update_date = pyqtSignal(str)
    
    # 处理业务逻辑
    def run(self):
        while True:
            data = QDateTime.currentDateTime()
            currTime = data.toString("yyyy-MM-dd hh:mm:ss")
            self.update_date.emit( str(currTime) )
            time.sleep(1)

class Window(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle('PyQt 5界面实时更新例子')
        self.resize(400, 100)
        self.input = QLineEdit(self)
        self.input.resize(400, 100)
        self.initUI()

    def initUI(self):
        # 创建线程
        self.backend = BackendThread()
        # 连接信号
        self.backend.update_date.connect(self.handleDisplay)
        self.thread = QThread()
        self.backend.moveToThread(self.thread)
        # 开始线程
        self.thread.started.connect(self.backend.run)
        self.thread.start()

    # 将当前时间输出到文本框
    def handleDisplay(self, data):
        self.input.setText(data)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    win.show() 
    sys.exit(app.exec_())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题