头文件
#include <QSerialPort>
#include <QSerialPortInfo>
模块
QT += core gui serialport
编程步骤
配置一个ui界面,五个QComboBox和一个按钮和一个QTextEdit
添加一个成员
private:QSerialPort *serial;
在构造函数中初始化ui端口列表和串口
//获取当前主机上所有可用的端口QList<QSerialPortInfo> list = QSerialPortInfo::availablePorts();//将获取的端口列表设置到ui界面上for(int i=0; i<list.size(); i++){ui->comboBox_port->addItem(list.at(i).portName());}//串口对象serial = new QSerialPort;//关联串口收到数据就会触发QSerialPort::readyRead信号,然后显示出来connect(serial,&QSerialPort::readyRead,this,[&](){//读取数据QByteArray data = serial->readAll();//显示ui->textEdit->append(data);});
连接按钮点击函数
//设置串口端口serial->setPort(QSerialPortInfo(ui->comboBox_port->currentText()));//1、设置波特率if(ui->comboBox_baud->currentText() == "9600"){serial->setBaudRate(QSerialPort::Baud9600);}else if(ui->comboBox_baud->currentText() == "115200"){serial->setBaudRate(QSerialPort::Baud115200);}else if(ui->comboBox_baud->currentText() == "38400"){serial->setBaudRate(QSerialPort::Baud38400);}//2、设置数据位if(ui->comboBox_dataBits->currentText() == "5"){serial->setDataBits(QSerialPort::Data5);}else if(ui->comboBox_dataBits->currentText() == "6"){serial->setDataBits(QSerialPort::Data6);}else if(ui->comboBox_dataBits->currentText() == "7"){serial->setDataBits(QSerialPort::Data7);}else if(ui->comboBox_dataBits->currentText() == "8"){serial->setDataBits(QSerialPort::Data8);}//3、设置奇偶校验位if(ui->comboBox_parity->currentText() == "None"){serial->setParity(QSerialPort::NoParity);}//4、设置停止位if(ui->comboBox_stopBits->currentText() == "1.5"){serial->setStopBits(QSerialPort::OneAndHalfStop);}else if(ui->comboBox_stopBits->currentText() == "1"){serial->setStopBits(QSerialPort::OneStop);}else if(ui->comboBox_stopBits->currentText() == "2"){serial->setStopBits(QSerialPort::TwoStop);}//5、打开串口serial->open(QIODevice::ReadWrite);