代码之家  ›  专栏  ›  技术社区  ›  K.Mulier

PyQt5:如何将QObject移动到主线程?

  •  4
  • K.Mulier  · 技术社区  · 6 年前

    我知道总的来说, QObject() 实例应该在主线程中创建。我也知道,一旦创建,你可以移动 QObject() 从主线程到另一个线程:

    可以找到官方的Qt文档 here

        # Worker-object approach
        # -----------------------
        # Note: these codelines execute in the main thread.
        workerThread = QThread()
        workerObj = WorkerObj()
        workerObj.moveToThread(workerThread)
    


    目前,我面临着完全相反的问题。我有一个 QObject() 在a中实例化(非主) QThread .我想把它移到主线程,如下所示:

        # Move a QObject() to the main thread
        # ------------------------------------
        # Note: these codelines execute in some QThread
        myObj = QObject()
        myObj.moveToThread(threading.main_thread())
    

    我得到以下错误:

    TypeError:moveToThread(self,QThread):参数1具有意外的类型“\u MainThread”

    我可能会因为主线程不是真正的 QThread .我该怎么做才能让它工作?


    编辑:
    显然答案是对的 in the documentation 关于 moveToThread() 作用这太尴尬了。我真诚的道歉。下次我会更小心的。


    1 回复  |  直到 6 年前
        1
  •  4
  •   Kuba hasn't forgotten Monica    6 年前

    QObject 当然,可以在任何线程中创建实例。它们是的,如果没有它,Qt将毫无用处。您要寻找的是全局应用程序对象及其线程:

    myObj = QObject()
    mainThread = QCoreApplication.instance().thread()
    myObj.moveToThread(mainThread)
    

    从当前线程调用对象上的任何非线程安全方法是未定义的行为 moveToThread 呼叫通过此调用,对象的非线程安全方法只能从目标线程安全使用。