classTcpComm:publicQThread
{
Q_OBJECT
public:
TcpComm(const QString &iAddrStr, quint16 iPort);
~TcpComm();
........
private:
.......
TcpClient*mTcpClient;
};
TcpComm::TcpComm(const QString &iAddrStr, quint16 iPort):mAddr(iAddrStr), mPort(iPort)
{
mIsStop = false;
mTcpClient = new TcpClient();
start();
}
以上程序在运行时报QObject: Cannot create children for a parent that is in a different thread错误。
将原构造函数中的mTcpClient = new TcpClient();放到run()中问题解决。
TcpComm::TcpComm(const QString &iAddrStr, quint16 iPort):mAddr(iAddrStr), mPort(iPort)
{
mIsStop = false;
start();
}
void TcpComm::run()
{
mTcpClient = new TcpClient();
........
}
查了查,原因应该是,在QThread中定义的所有东西都属于创建该QThread的线程。所以在构造函数中初始化的mTcpClient应该是属于父线程的,那么在run中调用时就属于跨线程调用。所以把mTcpClient放到run中初始化就属于线程的了,调用时就不会出现跨线程调用的问题。
同类问题1:在QThread中的run()函数里面的 调用QProcess对象 运行ping功能 但是显示
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QProcess(0x94d3008), parent's thread is QThread(0x3e4db0), current thread is Test_NetWork(0x94d29e8
请问问题出在哪里?
转载自: