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就沒有這個錯誤了,原理不懂,誰能解釋下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章