1.在Widget.h的peivate下添加串口的私有变量
QSerialPort * serialport;//私有串口对象
2.在Widget.cpp的构造函数中创建变量
serialport=new QSerialPort(this);//串口对象(对象属于我们窗口)
3.实现按键打开串口的功能(右键点击转到槽函数)
void Widget::on_btn_close_clicked()
{
//1.选择端口号
serialport->setPortName(ui->cm_serialNum->currentText());
//2.配置串口参数(校验位,波特率,数据位,停止位,流控)
serialport->setBaudRate(ui->cm_botelv->currentText().toInt());
serialport->setDataBits(QSerialPort::DataBits(ui->cm_shujvwei->currentText().toUInt()));
serialport->setStopBits(QSerialPort::StopBits(ui->cm_stopwei->currentText().toUInt()));
if(ui->cm_liukong->currentText()=="None")
{
serialport->setFlowControl(QSerialPort::NoFlowControl);
}
switch (ui->cm_jiaoyanwei->currentText().toInt())
{
case 0:
serialport->setParity(QSerialPort::NoParity);
break;
case 1:
serialport->setParity(QSerialPort::EvenParity);
break;
case 2:
serialport->setParity(QSerialPort::MarkParity);
break;
case 3:
serialport->setParity(QSerialPort::OddParity);
break;
case 4:
serialport->setParity(QSerialPort::SpaceParity);
break;
default:
serialport->setParity(QSerialPort::UnknownParity);
break;
}
//3.打开串口
if(serialport->open(QIODevice::ReadWrite))
{
qDebug()<<"serial open secusses!";
ui->btn_close->setText("关闭串口");
}
}