Unsolved Cannot create children for a parent that is in a different thread.
-
Hi
I have two thread :1- Main thread GUi 2-server_Thread(class of QThread)
in server_Thread I create udpsocket like this ://server_Thread.h private : QUdpSocket *udpSocket; //server_Thread.c void thread_server::run(){ . . udpSocket = new QUdpSocket(this); }
but when thread_server.c start and go to run function. I see this error: "QObject: Cannot create children for a parent that is in a different thread.
(Parent is QUdpSocket(0x691e40), parent's thread is QThread(0x610090), current thread is thread_server(0x7fffffffe300)" -
@Alexanov said in Cannot create children for a parent that is in a different thread.:
//server_Thread.c void thread_server::run(){ . . udpSocket = new QUdpSocket(this); }
thread_server
is a QObject that lives in the main thread. Therefore, you cannot make it the parent for any QObjects that you create in your thread.Why do you pass
this
to the QUdpSocket constructor? -
Hi Alexanov! As JKSH points out, all QObject instances (and instances from derived classes of course) in a "family" (that is with parent / child relation) have to live in the same thread. Beside other things this is very important for signal / slots and everything going through the event queue. You can push instances between threads, as long as they have no parent, see
void QObject::moveToThread(QThread *targetThread)
. Make sure you have a clear understanding which family belongs to which thread.
Be aware that signal / slot mechanism works differently depending on the thread-affinity of sender and receiver. As starting point you could checkenum Qt::ConnectionType
-
-
@jsulm
did you say delete "this" from my object like below? (object without any parent)udpSocket = new QUdpSocket();
-
@Alexanov yes
-
@Alexanov You still have to remember to delete it though. There are 3 ways:
- connect some signal (QThread::finished?) to the deleteLater slot
- delete it manually in QThread's destructor
- use smart pointers.
I'd go for the 3rd, change
QUdpSocket *udpSocket;
tostd::unique_ptr<QUdpSocket> udpSocket;