QT使用多线程报错,QObject: Cannot create children for a parent that is in a different thread.

看了几篇文章都没看懂
https://blog.csdn.net/qq_24890953/article/details/55880043
https://www.cnblogs.com/findumars/p/9361993.html

报错信息

QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0x32a5c10), parent’s thread is QThread(0x32902c0), current thread is QThread(0x18fe1a8)

没修改前的代码

//maindata.cpp
void mainData::initSerialPort()
{
    
    
    serialPort = new SerialThread;
    serialThread = new QThread(this);


    serialPort->moveToThread(serialThread);
    serialThread->start();

    connect(serialPort, &SerialThread::getcomPortList,this,&mainData::updateComPort);
    connect(this,&mainData::destroyed,this,&mainData::closeSerialThread);
    connect(serialPort, &SerialThread::receData, this, &mainData::handleReData);
}
SerialThread::SerialThread(QObject *parent) : QObject(parent)
{
    
    
    initSerial();
}
void SerialThread::initSerial()
{
    
    
    m_serial = new QSerialPort(this);//注意这里

    getPortNum();

//    connect(m_serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &SerialThread::handleSerialError);
    connect(m_serial, &QSerialPort::readyRead, this, &SerialThread::receiveData);
}

将上述的m_serial = new QSerialPort(this);改为
m_serial = new QSerialPort();即去掉this就没有这个错误了,原理不懂,谁能解释下。

猜你喜欢

转载自blog.csdn.net/weixin_43387612/article/details/106306751
今日推荐