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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
云中飞鸿16 小时前
如何编译编译 Qwt-5.2.0?
qt
雾岛听蓝1 天前
Qt 输入与多元素控件详解
开发语言·经验分享·笔记·qt
怎么没有名字注册了啊1 天前
解决qt制作软件.app迁移问题(发布)Mac
开发语言·qt
輕華2 天前
PyQt5入门实战:安装、QtDesigner设计与PyUIC转换完整指南
开发语言·qt
雾岛听蓝2 天前
Qt Widget控件属性详解
开发语言·经验分享·笔记·qt
大橘2 天前
【qml-5.1】qml与c++交互(QML_ELEMENT/QML_SINGLETON)
开发语言·c++·qt·交互·qml
雾岛听蓝2 天前
Qt按钮与标签控件详解
开发语言·经验分享·笔记·qt
碎碎念的安静2 天前
WPF 与 Qt 进程间通信(IPC)
开发语言·qt·wpf
(Charon)2 天前
【Qt/C++】Qt/C++ 中 :: 和 . 到底有什么区别?
开发语言·c++·qt
苕皮蓝牙土豆3 天前
Qt图形视图框架入门:坐标系统与鼠标事件处理详解
c++·qt