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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
blueman888818 小时前
qt5-serialbus详细解析
开发语言·网络·qt
杜子不疼.1 天前
【Qt初识】信号槽(三):机制意义、断开连接与 Lambda 表达式
开发语言·数据库·qt
杜子不疼.2 天前
【Qt初识】信号槽(二):自定义信号函数与槽函数
开发语言·qt
秋田君2 天前
Qt_QVariant
开发语言·qt
杜子不疼.2 天前
【Qt初识】工程起步:项目创建、代码解读与对象树
数据库·c++·qt
安东尼肉店2 天前
QT 自定义随机验证码校验
开发语言·qt
小徐不徐说3 天前
Qt 线程迁移机制完整实战指南(moveToThread)
开发语言·c++·qt·程序设计
Traveler飞3 天前
Ubuntu20.04 VMware 黑屏无法进入桌面,Ctrl+Alt+F2 可以进入终端,最终发现是磁盘空间满了
qt·ubuntu
m0_587098994 天前
Qt,二进制文件读写建议
开发语言·qt
秋田君4 天前
QT_QT信号与槽机制
开发语言·数据库·qt