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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
浅碎时光80727 分钟前
Qt (信号与槽 Widget控件 qrc文件)
开发语言·qt
郝学胜-神的一滴36 分钟前
跨平台通信的艺术与哲学:Qt与Linux Socket的深度对话
linux·服务器·开发语言·网络·c++·qt·软件构建
初次见面我叫泰隆10 小时前
Qt——3、常用控件
开发语言·qt·客户端
无小道11 小时前
Qt——QWidget
开发语言·qt
派葛穆14 小时前
Python-PyQt5 安装与配置教程
开发语言·python·qt
初次见面我叫泰隆16 小时前
Qt——4、Qt窗口
开发语言·qt·客户端开发
墨月白18 小时前
[QT]QProcess的相关使用
android·开发语言·qt
小小码农Come on18 小时前
QT信号槽机制原理
开发语言·qt
未来可期LJ19 小时前
【Qt 问题合集】Qt报错:No executable specified 如何解决呢?
qt
LYOBOYI12319 小时前
QML 中 Item、Window、Popup、Rectangle使用手册
qt