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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
kaixin_learn_qt_ing10 小时前
model/view 筛选功能
qt
佳児素花痴╮13 小时前
Qt速通2
开发语言·qt
心态还需努力呀14 小时前
把 Flameshot 编译进鸿蒙 PC:一次 Qt C++ 截图工具的源码级移植实战
c++·qt·harmonyos
CodeMaker80816 小时前
规则更规范,应用却起不来:我重新理解了 Qt Agent Skills
qt
楚莫识16 小时前
Qt show()、raise()、activateWindow() 调用顺序区别
qt·pyqt
励志不掉头发的内向程序员17 小时前
【LibreCAD 2D架构】从 addHistory 到 RS_UndoCycle:LibreCAD 里的两套 History 与撤销机制
开发语言·c++·qt·学习·系统架构
kaixin_learn_qt_ing1 天前
【银河麒麟下】 安装达梦数据库 + 使用Qt访问达梦数据库
qt
mengzhi啊1 天前
缓存类CacheDataManager把临时数据存入json。做成插件·
qt·缓存·json
尘客-追梦1 天前
Day 01:插件化之前,先看清 ABI 这堵墙
开发语言·c++·qt
Quz1 天前
QML SwipeView:实现一个简单的图片浏览器
qt