QT +=serialport
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
QSerialPort * testport=new QSerialPort();
if(testport->isOpen()){
testport->clear();
testport->close();
}
testport->setPortName(portname);
testport->setBaudRate(boud.toInt()); //设置波特率
testport->setDataBits(QSerialPort::Data8); //8个数据位
testport->setParity(QSerialPort::NoParity); //无校验位
testport->setStopBits(QSerialPort::OneStop); //一个停止位
testport->setFlowControl(QSerialPort::NoFlowControl);
if(!testport->open(QIODevice::ReadWrite)){
qDebug()<<"串口打开失败";
war->warnxianshi("请更新串口!!!","串口打开失败!");
war->showNormal();
// QMessageBox::information(this,"串口打开失败","请更新串口!!!!");
testport->setDataTerminalReady(true);
connect(testport,SIGNAL(readyRead()),this,SLOT(recvdeal())); //绑定串口读取数据槽
串口的读取槽:
void MainWindow:: recvdeal()
{
QString s=testport->readAll();
}
comboBox串口刷新:
ui->comboBox->clear();
foreach(const QSerialPortInfo & info,QSerialPortInfo::availablePorts()){
ui->comboBox->addItem(info.portName());
}
ui->comboBox->setCurrentIndex(-1);