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

this->moveToThread(thread);编译时程序输出:

QObject: Cannot create children for a parent that is in a different thread.
(Parent is SerialPort(0x6c48140), parent's thread is QThread(0x6c4a338), current thread is QThread(0x219e750)

以如下代码为例:

cpp 复制代码
SerialPort::SerialPort()
: m_thread(nullptr)
    , m_port(nullptr)
{
	//! 1
	//正确的,不输出警告信息的
    init_serialport();
    tts = new QTextToSpeech(this);
    init_thread();
    
    //! 2
	//错误的。输出如上述信息的
    //init_serialport();
    //init_thread();
    //tts = new QTextToSpeech(this);  //tts在SerialPort父类线程中创建
    
    //! 3
	//错误的。输出如上述信息的
    //tts = new QTextToSpeech(this);
    //init_thread();
    //init_serialport(); 			 //m_port在SerialPort父类线程中创建
    
    //! 4
	//错误的。输出如上述信息的
    //init_thread();
    //tts = new QTextToSpeech(this); //tts在SerialPort父类线程中创建
    //init_serialport(); 			 //m_port在SerialPort父类线程中创建
}


void SerialPort::init_thread()
{
    m_thread = new QThread;
    m_thread->setObjectName("串口线程");
    this->moveToThread(m_thread);
    connect(m_thread, &QThread::finished, this, &QThread::deleteLater);
    connect(m_thread, &QThread::finished, this, &SerialPort::deleteLater);
    m_thread->start();
}

void SerialPort::init_serialport()
{
    m_port = new QSerialPort();
}

总结:

  1. 在构造函数中定义的对象是在定义该类的线程中的
  2. 在将本类moveToThread后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
秋风&萧瑟3 小时前
【QT】QT控制硬件
开发语言·qt
爱编程的鱼12 小时前
JSON-RPC 2.0 规范中文版——无状态轻量级远程过程调用协议
前端·网络·qt·网络协议·rpc·json
m0_5557629014 小时前
vscode 配置qt
ide·vscode·qt
TechNomad18 小时前
Qt开发:JSON字符串的序列化和反序列化
qt·json
whoarethenext1 天前
初始https附带c/c++源码使用curl库调用
服务器·c++·qt·https·curl
enyp801 天前
麒麟系统(基于Ubuntu)上使用Qt编译时遇到“type_traits文件未找到”的错误
linux·qt·ubuntu
道剑剑非道1 天前
QT开发技术【qcustomplot 曲线与鼠标十字功能】
开发语言·qt·计算机外设
mahuifa2 天前
Qt内置图标速查表
qt·图标·qstyle·qicon
Ethon_王2 天前
走进Qt--QWidget基类详解
c++·qt
狗蛋儿l2 天前
qt 3d航迹图
开发语言·qt·3d