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中关于eventFilter函数无法过滤QTableWidget鼠标事件的处理方式
qt
奇树谦11 小时前
【Qt实战】实现图片缩放、平移与像素级查看功能
开发语言·qt
010米粉01013 小时前
Qt Cmake之路(一):Cmake变量语法
开发语言·qt·cmake
颜*鸣&空13 小时前
Qt Creator快速搭建项目
开发语言·qt
道剑剑非道13 小时前
Qt【使用libmodbus库】
开发语言·数据库·qt
林政硕(Cohen0415)14 小时前
T113 Qt5.15.2 G2D 旋转
qt·t113·g2d
布茹 ei ai14 小时前
QtWeatherApp - 简单天气预报软件(C++ Qt6)(附源码)
开发语言·c++·qt·开源·开源项目·天气预报
奇树谦15 小时前
Qt QDockWidget 深度解析:从基础使用到可保存布局的工程级主界面
开发语言·qt
不会c嘎嘎17 小时前
初识QT -- 第一个QT程序
开发语言·qt