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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
酷飞飞4 小时前
Qt Designer与事件处理
开发语言·qt·命令模式
mkhase6 小时前
9.12-QT-基本登陆界面实现
java·jvm·qt
咕噜咕噜啦啦6 小时前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
Quz7 小时前
QML Charts组件之折线图的鼠标交互
qt
眠りたいです9 小时前
基于脚手架微服务的视频点播系统-数据管理与网络通信部分的预备工作
c++·qt·ui·微服务·云原生·架构·媒体
bikong711 小时前
Qt/C++,windows多进程demo
c++·windows·qt
油炸自行车13 小时前
【Qt】Window环境下搭建Qt6、MSVC2022开发环境(无需提前安装Visual Studio)
qt·visual studio·qt6·msvc2022·qt creator 17.0
枫叶丹413 小时前
【Qt开发】显示类控件(三)-> QProgressBar
开发语言·qt
姓刘的哦1 天前
Qt中的QWebEngineView
数据库·c++·qt
SundayBear1 天前
QT零基础入门教程
c++·qt