Why cross-thread invoke will report “QObject: Cannot create children for a parent that is in a different thread.”?
-
Such as the title,confusing warning!Such as a member funcation of
QSerialPort
's instance invoked by child thread. I do not wanna get a solution,rahter than know why for the warning is given.//main.cpp int main(int argc, char *argv[]) { //... TestClass *testclass2 = TestClass::GetInstance(); TempMyThread *mythread = new TempMyThread; mythread->start(); //... } //tempthread.cpp void TempMyThread::run(){ TestClass *testclass2 = TestClass::GetInstance(); qDebug() << "temp thread " << testclass2; testclass2->myserialport->write("1"); }
myserialport
isTestClass
's member var. -
hi @Crawl.W
it's not a warning, its an error and not really confusing.
What is the issue exactly ?
Chances are, the the function is executed in the thread of the function caller. If you inside the function create a new QObject with for example
this
as parent, then you're trying to parent a Object to a parent that lives in a different thread compared to the creating thread. -
@Crawl.W said in Why cross-thread invoke will report “QObject: Cannot create children for a parent that is in a different thread.”?:
noting.
You are doing something or you would not have this error message.
If you don't want to show your code, then you will have to find yourself where you create a QObject instance with a parent in a different thread. -
now it's obvious.
Your singleton is created in the main thread. you write to it inside the worker thread. during write process, a QTimer is created and set, to monitor timeouts. That is created from the wrong thread of course. -> Therefore the error
-
-
@Crawl.W said in Why cross-thread invoke will report “QObject: Cannot create children for a parent that is in a different thread.”?:
Why do not call his timeout's slot function directly?
Because then it would be a synchronous call - write() would block until it's finished. But since it is an asynchronous API it should not block the caller.
-
@Crawl.W said in Why cross-thread invoke will report “QObject: Cannot create children for a parent that is in a different thread.”?:
Why do not call his timeout's slot function directly?
This is done to call the timeout function after all events in thread queue have been processed.
Here the extract for QTimer::interval:The default value for this property is 0. A QTimer with a timeout interval of 0 will time out as soon as all the events in the window system's event queue have been processed