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后声明的对象不在子线程创建,而是仍在其类被声明所在线程(就会报上述警告信息)
相关推荐
hqwest1 小时前
码上通QT实战16--监控页面08-连接后状态处理
qt·串口·信号与槽·serialport·通信过程·打开串口·com1
hqwest3 小时前
码上通QT实战15--监控页面07-打开串口连接
开发语言·qt·多线程·signal·slot·emit·信号和槽
CS Beginner5 小时前
【单片机】嵌入式显示屏开发框架:QT、SDL、LVGL 深度解析
单片机·嵌入式硬件·qt
金色熊族5 小时前
MV结构下设置Qt表格的代理(2)
c++·qt
Morwit5 小时前
Qt qml创建c++类的单例对象
开发语言·c++·qt
YxVoyager5 小时前
Qt C++ :QRegularExpression 正则表达式使用详解
c++·qt·正则表达式
qq_401700416 小时前
QStackedLayout 实现遮罩层
qt
Larry_Yanan6 小时前
Qt多进程(十一)Linux下socket通信
linux·开发语言·c++·qt
weixin_462446236 小时前
Python 使用 PyQt5 + Pandas 实现 Excel(xlsx)批量合并工具(带图形界面)
python·qt·pandas
不会c嘎嘎6 小时前
QT中的常用控件(五)
服务器·开发语言·qt