Qt:移动到线程

Qt: move to thread

假设我有:

Class A{
Q_Object

public:
A::A(){};
void A::init(){obj = new myQobject();}
myQobject* obj;
}

那么如果 Class A 像这样使用:

QThread *workerthread = new QThread;
A *worker = new A();
worker->moveToThread(workerthread);
workerthread->start();
worker->init();

那么 myQobject obj 将存在于哪个线程中?主线程还是辅助线程?

它将存在于主线程中,因为您是从主线程调用 worker->init()。您可以使用信号和槽从工作线程调用 init,或者使用 QMetaObject::invokeMethod 和排队连接 (您不必指定它,因为它将使用 Qt::AutoConnection 默认情况下,如果 invokeMethod 是从与接收对象不同的线程调用的,则将使用 Qt::QueuedConnection).

QMetaObject::invokeMethod(worker, "init",
                       Qt::QueuedConnection);

您也可以在构造函数中创建 myObject 并将 this 设置为父级。然后当你调用 moveToThread 时,该对象也会将它的子对象移动到同一个线程。

QObject::moveToThread: Changes the thread affinity for this object and its children.