Emitting signals from a Python thread using QObject

前端 未结 2 692
面向向阳花
面向向阳花 2021-01-12 20:20

I would like to know what are the consequences of emitting a signal from a regular python thread within a QObject, compared with a QThread.

See the following class:<

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 20:31

    I would like to add:

    class MyQThread(QThread):
        signal = pyqtSignal() # This thread emits this at some point.
    
    class MainThreadObject(QObject):
        def __init__(self):
            thread = MyQThread()
            thread.signal.connect(self.mainThreadSlot)
            thread.start()
    
        @pyqtSlot()
        def mainThreadSlot(self):
            pass
    

    This is perfectly OK, according to all documentation I know of. As is the following:

    class MyQObject(QObject):
        signal = pyqtSignal()
    
    class MainThreadObject(QObject):
        def __init__(self):
            self.obj = MyQObject()
            self.obj.signal.connect(self.mainThreadSlot)
            self.thread = threading.Thread(target=self.callback)
            self.thread.start()
    
        def callback(self):
            self.obj.signal.emit()
    
        @pyqtSlot()
        def mainThreadSlot(self):
            pass
    

    From what @ekhumoro is saying, those two are functionally the same thing. Because a QThread is just a QObject who's run() method is the target= of a threading.Thread.

    In other words, both the MyQThread's and the MyQObject's signal is memory "owned" by the main thread, but accessed from child threads.

    Therefore the following should also be safe:

    class MainThreadObject(QObject):
        signal = pyqtSignal() # Connect to this signal from QML or Python
    
        def __init__(self):
            self.thread = threading.Thread(target=self.callback)
            self.thread.start()
    
        def callback(self):
            self.signal.emit()
    

    Please correct me if I am wrong. It would be very nice to have official documentation on this behavior from Qt and/or Riverbank.

提交回复
热议问题