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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
颜*鸣&空5 小时前
QT实现串口通信+VSPD+串口调试工具
开发语言·qt
颜*鸣&空9 小时前
QT程序实现串口通信案例
开发语言·qt
Main. 249 小时前
从0到1学习Qt -- 常见控件之显示类控件
qt·学习
qq_4017004115 小时前
Qt中事件循环与并发机制的协同工作
qt
qq_401700412 天前
Qt Positioning 模块访问设备地理位置信息
开发语言·qt
闫有尽意无琼2 天前
银河麒麟v11 arm编译Qt creator8.0.2报错
开发语言·qt
lqj_本人2 天前
鸿蒙Qt触控疑云:事件传递丢失与坐标偏移修复
qt·华为·harmonyos
_OP_CHEN2 天前
从零开始的Qt开发指南:(五)Qt 常用控件之 QWidget(上):解锁 Qt 界面开发的核心基石
开发语言·c++·qt·前端开发·qwidget·gui开发·qt常用控件
happyjoey2172 天前
使用Qt自带的Maintenance Tool将Qt6.9升级为QT6.10
开发语言·qt
lqj_本人2 天前
鸿蒙Qt生命周期:后台被杀后的数据自救
qt·华为·harmonyos