说明
工作上遇到需要等待接收对端返回结果,才进行后续处理的情况,可以使用QEventLoop和QTimer::singleShot实现。
部分代码
串口初始化
void serialport::Init(const QSettings& settings)
{
m_ptrSerialPort = new QSerialPort(this);
m_ptrSerialPort->setPortName(settings.value("ladserport/portname","COM8").toString());
m_ptrSerialPort->setBaudRate(settings.value("ladserport/baudrate",921600).toInt());
m_ptrSerialPort->setParity(QSerialPort::NoParity);
m_ptrSerialPort->setDataBits(QSerialPort::Data8);
m_ptrSerialPort->setStopBits(QSerialPort::OneStop);
}
同步接口实现
bool serialport::WriteForResponse(const QByteArray &data, QByteArray &responseMsg)
{
m_ptrSerialPort->clear();
bool state = true;
QEventLoop loop;
auto async = QObject::connect(m_ptrSerialPort, &QSerialPort::readyRead, [&, this] {
responseMsg = m_ptrSerialPort->readAll();
qDebug()<<"responseMsg:"<<responseMsg.toHex();
emit Finshed();
});
m_ptrSerialPort->write(data);
m_ptrSerialPort->waitForBytesWritten();
QTimer::singleShot(3000,this,[&](){
qDebug()<<"singleShot:";
emit Finshed();
state=false;
});
connect(this,&serialport::Finshed,&loop,&QEventLoop::quit);
loop.exec();
QObject::disconnect(async);
return state;
}