Unsolved QObject: Cannot create children for a parent that is in a different thread, but it works, why?
-
class MyThread : public QThread { public: virtual void run() { networkReply = networkAccessManager.get(QNetworkRequest(url)); } private: QNetworkAccessManager networkAccessManager; }
Runtime message:
QObject: Cannot create children for a parent that is in a different thread. (Parent is QNetworkAccessManager(0x243bb066390), parent's thread is QThread(0x243b78951b0), current thread is StockIDUpdateTask(0x243bb066380)
The message is caused by
QNetworkAccessManager ::get()
, but the function return a valid object pointer, and when connectnetworkReply.finished
to a slot, it works.What to do with the runtime message?
-
@jronald networkAccessManager is part of MyThread which itself is not the thread it manages. That means: run() is executed in the second thread but networkAccessManager is living in the thread which created MyThread instance. You should just create QNetworkAccessManager instance in run():
class MyThread : public QThread { public: virtual void run() { networkAccessManager = new QNetworkAccessManager(); networkReply = networkAccessManager->get(QNetworkRequest(url)); } private: QNetworkAccessManager *networkAccessManager; }
-
This post is deleted! -
Yes,
networkAccessManager .thread()
is notMyThread
, this is what confuses me, it works! Why?
BTW, ifnetworkAccessManager
can be reused by multiple threads, it'll be appreciated. -
@jronald You should read this: https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
It can work even if the instance is in another thread, but you should make sure it is in the same thread to avoid issues. -
@jronald said in QObject: Cannot create children for a parent that is in a different thread, but it works, why?:
it works! Why?
This is called "Undefined Behaviour". It doesn't follow the rules, but it seems to work. However, the problem is: it might suddenly stop working in the future.
So, don't use it, even though it works now.
if
networkAccessManager
can be reused by multiple threads, it'll be appreciated.QNetworkAccessManager
is meant for be used from 1 thread only. I recommend that you design your software to only use it from 1 thread: When your main thread finishes downloading, emit a signal to send the data to another thread.Anyway, may I ask why you want to use multiple threads?