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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
范纹杉想快点毕业1 小时前
Google C++ Style Guide 谷歌 C++编码风格指南,深入理解华为与谷歌的编程规范——C和C++实践指南
c语言·数据结构·c++·qt·算法
幸运黒锦鲤1 小时前
Qt5、C++11 获取wifi列表与wifi连接
开发语言·qt
朱小勇本勇4 小时前
QT+R&SVisa控制LXI仪器
开发语言·qt
玉带湖水位记录员4 小时前
Qt+线段拖曳示例代码
开发语言·c++·qt
vegetablesssss5 小时前
QGrphicsScen画布网格和QGrphicsItem对齐到网格
c++·qt
计算机内卷的N天10 小时前
QT的自定义控件
qt
程序员Jared12 小时前
Qt—模态与非模态对话框
c++·qt
TNTLWT1 天前
Qt功能区:Ribbon控件
开发语言·qt
cykaw25901 天前
QT中信号和事件的区别
开发语言·qt
yxc_inspire1 天前
基于Qt的app开发第十天
开发语言·c++·qt·app