1.Qt解决运行程序后,可用串口变化问题
2.设置定时器,定时刷新可用串口
//定义全局变量
QSerialPort *serialPort;
QTimer *timer;
QStringList portStringList;
QString currentCOM = "";
//在主函数
timer = new QTimer; //定时扫描和更新串口
connect(timer,&QTimer::timeout,this,&Widget::showValidPort);
//实时更新端口号
timer->start(1000);
//每1000ms定时检测串口状态
serialPort = new QSerialPort;
//实例化串口对象
foreach(const QSerialPortInfo &info,
QSerialPortInfo::availablePorts()) //扫描可用串口
portStringList += info.portName();
ui->com->addItems(portStringList);
//更新并检测串口函数实现
void showValidPort()
{
QStringList newPortStringList;
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
newPortStringList += info.portName();
if(newPortStringList.size() != portStringList.size())
{
portStringList = newPortStringList;
ui->com->clear();
ui->com->addItems(portStringList);
}
if(currentCOM != ui->com->currentText()) //串口突然断开连接了
{
currentCOM = ui->com->currentText();
if("关闭" == ui->comSwitchBtn->text())
{
on_comSwitchBtn_clicked();
}
}
}
void on_comSwitchBtn_clicked()
{
if("打开" == ui->comSwitchBtn->text())
{
currentCOM = ui->com->currentText();
serialPort->setPortName(currentCOM); //获取串口号
if(serialPort->open(QIODevice::ReadWrite)) //如果打开串口成功
{
//...
}
}
else if("关闭" == ui->comSwitchBtn->text())
{
ui->comSwitchBtn->setText("打开");
serialPort->close();
}
}