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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
满天星83035779 小时前
【Qt】信号和槽(二) (自定义信号和槽)
开发语言·数据库·qt
Jun62610 小时前
QT(19)-VISA控制仪器
开发语言·qt
Jun62612 小时前
QT(2)-通过管道关联CMD
开发语言·qt·命令模式
峰上踏雪14 小时前
Windows 下最推荐的 Qt + VS2026 + CMake 开发方案
开发语言·windows·qt
郝学胜-神的一滴15 小时前
Qt 高级开发 027: QTabWidget自定义样式表美化实战
开发语言·c++·qt·程序人生·软件构建·用户界面
listhi52015 小时前
基于 Qt 5.8.0 的串口调试助手
开发语言·qt
sycmancia16 小时前
Qt——Qt程序打包
开发语言·qt
郝学胜-神的一滴16 小时前
Qt 高级开发 026:QTabWidget御道,从筑基到化境
开发语言·c++·qt·程序人生·软件构建·用户界面
Jun62616 小时前
QT(14)-UBUNTU下QT使用串口
开发语言·qt·ubuntu
Jun62616 小时前
QT(16)-云端版本管理
开发语言·qt