假设我创建了一个 QObject a
并且它有一个成员 QObject b
。 (其实A和B都是QObject的子类,A类有一个成员Bb
。)
当 b
被创建时,它的父级是 0(默认)。在代码中,如果我从未将 b
的父级设置为 a
,并且如果我调用 movetothread()
来移动 a
进入一个工作线程,b
是否也会被移入该线程?
如果它没有被移动,如果我从工作线程(我将 a
移动到其中的线程)调用 b.init()
,它使用 new 运算符创建另一个以 b
作为父对象的 QObject,那么我会得到以下错误,对吗?
QObject: Cannot create children for a parent that is in a different thread
最佳答案
正如 QObject::moveToThread 的 Qt 文档所述:-
Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.
在这种情况下,父项是一个对象,其子项是通过在构造函数中传递父项或通过对子项调用 setParent 来设置的。它不是具有指向另一个对象的指针的对象。
In the code, if I never set b's parent to a, and if I call movetothread() to move a into a worker thread, will b be moved into that thread too?
所以,不,如果 b 的父级未设置并且您在 'a' 上调用 moveToThread,'b' 仍将具有原始线程关联。
If it is not moved, if I call b.init() from the worker thread...
如果您将“a”而不是“b”移动到工作线程,那么您不应该直接从工作线程调用 b.init。相反,工作线程 ('a') 中的对象应该发出信号,让原始线程中的对象从连接的槽中调用 b.init
关于c++ - Qt moveToThread : What resources are brought with the object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452850/