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 小时前
详谈 QLayout::SizeConstraint 和 QSizePolicy 对 QWidget 尺寸的影响
c++·qt
王廷胡_白嫖帝8 小时前
Qt网络速度测试工具开发教程 - 从零开始构建网络测速应用
开发语言·网络·qt
qq_259297247321 小时前
QT-窗口类部件
c++·qt
楚Y6同学1 天前
QT之QSS的使用方法和常用控件的样式设置
开发语言·qt
Zafir20242 天前
Qt实现TabWidget通过addTab函数添加的页,页内控件自适应窗口大小
开发语言·c++·qt·ui
王廷胡_白嫖帝2 天前
Qt文件压缩工具项目开发教程
java·开发语言·qt
牵牛老人2 天前
Qt 插件开发全解析:从接口定义,插件封装,插件调用到插件间的通信
开发语言·qt
机器视觉知识推荐、就业指导2 天前
面试问题详解五:Qt 信号与槽的动态管理
开发语言·qt
四维碎片3 天前
【Qt】线程池与全局信号实现异步协作
开发语言·qt·ui·visual studio
feiyangqingyun3 天前
纯Qt结合ffmpeg实现本地摄像头采集/桌面采集/应用程序窗口采集/指定采集帧率和分辨率等
qt·ffmpeg·qt桌面采集·qt摄像头采集·qt程序窗口采集