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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
不想看见4041 小时前
C++/Qt 实习岗位深度解析【结合一次研发实习谈感受】
开发语言·c++·qt
羊小猪~~6 小时前
【QT】-- QMainWindow简介
开发语言·数据库·c++·后端·qt·前端框架·求职招聘
CSCN新手听安8 小时前
【Qt】Qt概述(三)Qt初识,HelloWorld的创建,对象树
开发语言·qt
code_计梦星河10 小时前
Qt 开发第九天:时间控件 / 正则 / Vector / 主界面优化实操
qt
小温冲冲10 小时前
Qt WindowContainer 进阶指南:底层原理、性能优化与架构抉择
qt·性能优化·架构
徐某人..11 小时前
基于i.MX6ULL开发板与OV5640摄像头实现QT相机应用开发
qt·学习·arm
qq_401700411 天前
Qt 数据库操作详解:从连接到增删改查
qt
天天学IT1 天前
第三章 Qt 编译及安装
开发语言·qt·qt教程·qt6教程
weixin_464307631 天前
QT插件系统
qt
Summer_Uncle1 天前
【QT学习】Qt界面布局的生命周期和加载时机
c++·qt