migrating from Inherited QThread to Worker model

后端 未结 3 343
失恋的感觉
失恋的感觉 2021-01-23 00:36

So through a lot of help in my previous questions (Interrupting QThread sleep and PySide passing signals from QThread to a slot in another QThread) I decided to attempt to chang

3条回答
  •  北海茫月
    2021-01-23 00:51

    The first issue is that you need to connect your myObject.do_work method to QThread.started:

    self.myRunThread.started.connect(self.myRunObj.do_work)
    

    Secondly, your do_work method should include something along these lines to enable event processing (please forgive my rusty PyQt and pseudocode):

    def do_work(self):
        while someCondition:
            #The next two lines are critical for events and queued signals
            if self.thread().eventDispatcher().hasPendingEvents():
                self.thread().eventDispatcher().processEvents(QEventLoop.AllEvents)
            if not self.meetsSomeConditionToContinueRunning():
                break
            elif self.hasWorkOfSomeKind():
                self.do_something_here()
            else:
                QThread.yieldCurrentThread()
    

    For more on this, check out the docs for QAbstractEventDispatcher.

    The logic here is that when a signal is emitted from one thread (myWidget.datagramHandled), it gets queued in your worker thread's event loop. Calling processEvents processes any pending events (including queued signals, which are really just events), invoking the appropriate slots for any queued signals (myRunObj.packet_handled).

    Further reading:

    • How To Really, Truly Use QThreads; The Full Explanation
    • Threading Basics

提交回复
热议问题