QObject: Cannot create children for a parent that is in a different thread错误

落日映苍穹つ 2022-01-30 14:43 317阅读 0赞

QObject: Cannot create children for a parent that is in a different thread错误

classTcpComm:publicQThread

{

  1. Q\_OBJECT

public:

  1. TcpComm(const QString &iAddrStr, quint16 iPort);
  2. ~TcpComm();
  3. ........

private:

  1. .......

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()

{

  1. mTcpClient = new TcpClient();
  2. ........

}

查了查,原因应该是,在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

classTcpComm:publicQThread

{

  1. Q\_OBJECT

public:

  1. TcpComm(const QString &iAddrStr, quint16 iPort);
  2. ~TcpComm();
  3. ........

private:

  1. .......

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()

{

  1. mTcpClient = new TcpClient();
  2. ........

}

查了查,原因应该是,在QThread中定义的所有东西都属于创建该QThread的线程。所以在构造函数中初始化的mTcpClient应该是属于父线程的,那么在run中调用时就属于跨线程调用。所以把mTcpClient放到run中初始化就属于线程的了,调用时就不会出现跨线程调用的问题。

发表评论

表情:
评论列表 (有 0 条评论,317人围观)

还没有评论,来说两句吧...

相关阅读