解决 QObject: Cannot create children for a parent that is in a different thread.

1. 错误 QObject: Cannot create children for a parent that is in a different thread.

Generally, such an error occurs when using multithreading Qtin and trying to use connectsignals and slots that connect to different or the same object.

The reason is Qtthat each object of will have an attribution, and such an error can be seen from the error message that the two bound objects are not working in the same thread (the thread IDis different), that is, the two objects Affiliation is different.

2. Solutions

In the author's original error code, the slot function binding the parent object and the current object in the thread class caused such a problem. Even if the problem is temporarily solved, the slot function will not execute after the signal is sent.

Then the author found another way not to completely adopt the solutions given by various gods on the Internet, but
<1> after the parent object creates the thread class, directly complete connectthe binding ;
<2> in the construction of the thread class Add code in the function this->moveToThread(this);to change the ownership of the current thread;
<3> and add code run()in this->exec();(generally added after all operations, before the loop wait)
[注]:this->exec() 的作用是循环消息事件的机制,因此添加之后槽函数便可正常的触发。

After this operation, your Qt Creatorwill no longer report an error, and the signal and slot functions can be triggered normally.

Supongo que te gusta

Origin blog.csdn.net/qq_36393978/article/details/128338447
Recomendado
Clasificación