鍍金池/ 問答/Python  C++  網(wǎng)絡(luò)安全/ PyQt5 多線程 子線程的任務(wù)怎么跑到主線程去運(yùn)行了?

PyQt5 多線程 子線程的任務(wù)怎么跑到主線程去運(yùn)行了?

我使用PyQt5寫GUI程序,老是出現(xiàn)“未響應(yīng)”的情況,將耗時(shí)操作放入到子線程去運(yùn)行也是如此,我寫了下面一個(gè)小程序來測試,發(fā)現(xiàn)這些任務(wù)的確是在主線程執(zhí)行的,各位大神來求解釋?我的代碼如下:

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
回答
編輯回答
尕筱澄

這樣寫

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

class BackendThread(QObject):
    # 通過類成員對象定義信號(hào)
    update_date = pyqtSignal(str)
    
    # 處理業(yè)務(wù)邏輯
    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界面實(shí)時(shí)更新例子')
        self.resize(400, 100)
        self.input = QLineEdit(self)
        self.input.resize(400, 100)
        self.initUI()

    def initUI(self):
        # 創(chuàng)建線程
        self.backend = BackendThread()
        # 連接信號(hào)
        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()

    # 將當(dāng)前時(shí)間輸出到文本框
    def handleDisplay(self, data):
        self.input.setText(data)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    win.show() 
    sys.exit(app.exec_())
2018年6月17日 13:50