Reputation: 69
Which is more appropriate: QThread or QFuture ? I'm trying to pass a QNetWorkAccessManager in a QThread but it causes an error with the parent and child thread :/
QObject: Cannot create children for a parent that is in a different thread. (Parent is QNetworkAccessManager(0xc996cf8), parent's thread is QThread(0xaba48d8), current thread is Citizen(0xca7ae08)
m_networkManger = new QNetworkAccessManager(this);
m_thread = new QThread();
m_data = new LoadData(m_labelsList, m_parserType, argUrl, m_networkManger);
m_data->moveToThread(m_thread);
connect(m_thread, SIGNAL(started()), m_data, SLOT(process()));
connect(m_thread, SIGNAL(finished()), m_thread, SLOT(deleteLater()));
m_thread->start();
Could using QFuture solve the problem?
Upvotes: 1
Views: 1573
Reputation: 37512
The object which is moved to other thread must not have a parent. Qt is designed in such way that whole object tree must be in one thread (object is moved to other thread with all its children).
If object has a parent it is moveToThread
will fail (do nothing only prints error in logs).
QFuture doesn't change anything in this case.
Note that you can run object methods in different thread then object belongs to. If objects belong to some thread it means that connected slots of this object will tend to be called from this thread (only if connection type was Qt::DirectConnection
slot can be invoked from different thread).
Upvotes: 2
Reputation: 27611
My first thought was why do you want to move the networkManager to a different thread anyway?
Anyhow, the problem you see is that when you move an object to a new thread, it moves the object and its children.
You create m_networkManager and pass 'this' to it, making that object its parent. Whatever that object is, it will be residing on the original thread. You can't move a child object to a different thread from its parent.
Therefore, remove the parent object 'this' when creating the QNetworkAccessManager.
m_networkManger = new QNetworkAccessManager;
Ensure you handle deleting of the networkManager, now that it is no longer parented.
Upvotes: 2