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 小时前
06_Qt 常用数据类型与容器:QString、QList、QVector、QMap 的性能与实现分析
数据结构·qt
zlinear数据采集卡8 小时前
数据采集卡从入门到精通(38):上位机开发实战——Python/QT/LabVIEW的技术选型与分层架构
python·单片机·嵌入式硬件·qt·fpga开发·开源·labview
skr爱码士10 小时前
05_Qt 核心模块概览——Qt Core、Gui、Widgets、Quick 的职责划分
c++·qt·系统架构·客户端
MOONICK10 小时前
QT的UI开发框架
qt·ui
郝学胜-神的一滴11 小时前
Horse3D 游戏引擎研发笔记(七):Clydesdale——从流式日志到多输出订阅
c++·qt·unity·游戏引擎·图形渲染·unreal engine·opengl
NO121214 小时前
python pyqt5調用攝像頭實時顯示
开发语言·python·qt
丰锋ff1 天前
基于 Qt 的智慧社区物业管理系统
开发语言·qt
程与留1 天前
05_Qt 核心模块概览——Qt Core、Gui、Widgets、Quick 的职责划分
c++·qt
buhuizhiyuci1 天前
【QT-百日筑基篇】修真世界摸爬滚打多年,终于黄天不负有心人,突破炼器中期——常用控件QWight的属性
开发语言·c++·qt·gui·图形化
Littlehero_1211 天前
QT自定义控件之热换站系统(源码开源)
开发语言·qt