1、错误1
ASSERT failure in QCoreApplication::sendEvent: “Cannot send events to objects owned by a different thread. Current thread 0x0x2599c080. Receiver ‘’ (of type ‘QNativeSocketEngine’) was created in thread 0x0x2b0776b0”
如下代码,直接在mainwindow中调用DisConnect,会导致程序崩溃,且报错如上图。
原因:m_serial被移到线程中,只能在线程中调用,不能在主线程中直接调用
解决方法:使用信号槽调用DisConnect
出错过程分析:
//1、构造函数中将类移到了线程中
m_serial = NULL;
m_th = new QThread();
this->moveToThread(m_th);
//2、串口移到线程中
m_serial = new QSerialPort();
m_serial->moveToThread(m_th);
//3、断开连接
void ConnectSerial::DisConnect()
{
qDebug() << "this thread 2" << QThread::currentThread() <<"id" << QThread::currentThreadId();
if(m_serial != NULL)
{
if(m_serial->isOpen())
{
disconnect(m_serial,&QSerialPort::readyRead,this,&ConnectSerial::readData);
m_serial->close();
}
delete m_serial;
m_serial = NULL;
}
}
//在mainwindow中直接调用函数
m_SendSerial->DisConnect();
如下图:DisConnect函数所在线程与m_Serial所在线程不一致,DisConnect还在主线程中,
解决方法
//连接信号槽
connect(this,&ConnectSerial::disConnect,this,&ConnectSerial::DisConnect);
//在mainwindow中调用信号
m_SendSerial->disConnect();
如下图:DisConnect函数所在线程与mSerial所在线程一致。