QT报QObject: Cannot create children for a parent that is in a different thread.
今天在写多线程程序启动socket的时候,出现了这样的错误。
其原因是Qt中,不同线程中初始化的对象只能在该线程中使用,而不能在其他线程中使用。由于我写了如下代码:
private:
qintptr socketDecriptor;
int waitDuration = -1;
QTcpSocket socket;
QString basePath;
QMutex mutex;
QDir dir;//not used now
QObject *parent;
qintptr desc;
而该类在主线程里面初始化,初始化时顺便就初始化了socket,所以socket属于主线程,当我启动子线程,并在其中访问socket时,就出现了错误。正确的做法是:
private:
qintptr socketDecriptor;
int waitDuration = -1;
QTcpSocket *socket;
QString basePath;
QMutex mutex;
QDir dir;//not used now
QObject *parent;
qintptr desc;
然后再run()函数里面初始化该指针