QObject: cannot create children for a parent which is in a different thread
-
I have a thread class in which i have a TCP socket.
now whenever i run the application, i get a message saying "QObject: cannot create children for a parent which is in a different thread". I know it is because of the thread where i take the instance of class is different and the thread where i use the socket is different.my question is what problem can it cause in functionality.??
-
can u give some code snippet....
so that we can help u... -
QObjects interact with their parents and children. For performance reasons they do so in a non-threadsafe manner.
So your setup may result in data corruption and crashes. Better fix those messages!
-
@
// HEADER FILE ----------------------------------------#ifndef THREADCLASS_H
#define THREADCLASS_H#include <QObject>
#include <QThread>
#include <QtNetwork/QTcpSocket>class ThreadClass : public QThread
{
Q_OBJECTpublic:
ThreadClass(QString serverAddress, quint16 serverPort);
void run();protected:
QString ipAddr;
quint16 tcpPort;
QTcpSocket tcpSocket;
};#endif // THREADCLASS_H
// SOURCE FILE ----------------------------------------
#include "threadclass.h"
ThreadClass::ThreadClass(QString serverAddress, quint16 serverPort)
{
ipAddr = serverAddress;
tcpPort = serverPort;
}void ThreadClass::run()
{
tcpSocket.connectToHost(ipAddr, tcpPort);
if(tcpSocket.waitForConnected() == true)
{
qDebug() << "connected";
}
else
{
qDebug() << "timeout";
}
}// MAIN FILE ----------------------------------------
#include <QtCore/QCoreApplication>
#include "threadclass.h"int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ThreadClass threadClass("www.google.com", 80);threadClass.start(); return a.exec();
}
@ -
excellent answer tobias....
this will help him... -
IT GAVE ME FOLLOWING RUNTIME MESSAGES...
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTcpSocket(0xbf9ec2bc), parent's thread is QThread(0x92ab3e0), current thread is ThreadClass(0xbf9ec2ac)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTcpSocket(0xbf9ec2bc), parent's thread is QThread(0x92ab3e0), current thread is ThreadClass(0xbf9ec2ac) -
Check http://developer.qt.nokia.com/wiki/Threads_Events_QObjects for instructions on how to do this correctly.
-
On a sidenote: there is no need to use a seperate thread for just having asynchronous networking, as Qts networking classes already provide an non-blocking interface using signals and slots.