溫馨提示×

pyqt5線程跨調用對象怎么實現

小億
156
2023-11-04 11:58:55
欄目: 編程語言

在PyQt5中,要實現跨線程調用對象,可以使用QMetaObject.invokeMethod()方法。這個方法可以在指定的對象上調用一個槽函數,并將參數傳遞給它。

下面是一個示例,演示了如何在PyQt5中實現線程間的跨調用對象:

from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot, QMetaObject
from PyQt5.QtWidgets import QApplication

# 子線程類
class Worker(QThread):
    def __init__(self):
        super().__init__()

    def run(self):
        # 模擬耗時操作
        self.sleep(5)
        
        # 發送信號通知主線程
        self.emitSignal.emit('Hello from worker thread')

# 主線程類
class MainWindow(QObject):
    emitSignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()

    @pyqtSlot(str)
    def onEmitSignal(self, msg):
        print(msg)

    def startWorkerThread(self):
        self.worker = Worker()
        self.worker.emitSignal.connect(self.onEmitSignal)
        self.worker.start()

if __name__ == '__main__':
    app = QApplication([])
    mainWindow = MainWindow()

    # 在主線程中調用子線程的槽函數
    QMetaObject.invokeMethod(mainWindow, 'startWorkerThread', Qt.QueuedConnection)

    app.exec_()

在這個示例中,Worker類表示一個子線程,MainWindow類表示主線程。在Worker類中,使用emitSignal信號向主線程發送消息。在MainWindow類中,使用onEmitSignal槽函數接收并處理這個消息。

在主線程中,我們使用QMetaObject.invokeMethod()方法調用startWorkerThread槽函數,并指定連接類型為Qt.QueuedConnection,表示在主線程的事件循環中調用這個槽函數。

當子線程完成耗時操作后,會發射emitSignal信號,然后這個信號會被連接到主線程的onEmitSignal槽函數,從而實現了線程間的跨調用對象。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女