简体   繁体   English

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

[英]PyQt5: How to move a QObject to the main thread?

I know that in general, QObject() instances should be created in the main thread. 我知道通常应该在主线程中创建QObject()实例。 I also know that - once created - you can move a QObject() from the main thread to another one: 我也知道-创建后-您可以将QObject()从主线程移动到另一个线程:

official Qt docs can be found here 官方的Qt文档可以在这里找到

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


Currently I am facing the exact opposite problem. 目前,我正面临完全相反的问题。 I have a QObject() instantiated in a (non-main) QThread . 我有一个QObject()在(非主) QThread实例化。 I want to move it to the main thread, like this: 我想将其移至主线程,如下所示:

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

I get the following error: 我收到以下错误:

TypeError: moveToThread(self, QThread): argument 1 has unexpected type '_MainThread' TypeError:moveToThread(self,QThread):参数1具有意外的类型'_MainThread'

I probably get the error because the main thread is not a genuine QThread . 我可能会收到错误,因为主线程不是真正的QThread What should I do to make it work? 我应该怎么做才能使其正常工作?


EDIT: 编辑:
Apparently the answer was right in the documentation of the moveToThread() function. 显然答案在moveToThread()函数的文档中是正确 This is pretty embarrassing. 这真令人尴尬。 My sincere apologies. 诚挚的歉意。 I'll be more careful next time. 下次我会更加小心。


QObject instances can be created in any thread, of course. 当然,可以在任何线程中创建QObject实例。 And they are, and Qt would be quite useless without it. 而且他们是,没有它,Qt将毫无用处。 What you're looking for is the global application object - and its thread: 您正在寻找的是全局应用程序对象-及其线程:

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

It is undefined behavior to call, from the current thread, any non-thread-safe methods on the object after the moveToThread call. moveToThread调用之后,从当前线程调用对象上的任何非线程安全方法都是未定义的行为。 Past this call, the object's non-thread-safe methods can be safely used from the target thread only. 超过此调用之后,只能从目标线程安全地使用对象的非线程安全方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM