说明:版本为Qt5
1.在.pro文件中加入串口模块
QT += serialport
2.在.h文件中增加串口相关的头文件
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
3.在class中增减成员变量
QSerialPort *serialPort; // 建议使用指针,不使用变量
4.串口初始化
serialPort = new QSerialPort(this);
5.打开串口
member->serialPort->setPortName(ui->comboUartPort->currentText());
member->serialPort->setBaudRate(ui->comboUartBps->currentText().toUInt());
member->serialPort->setDataBits(ui->comboUartDataBits->currentText().toUInt());
if (ui->comboUartParity->currentText() == tr("无"))
member->serialPort->setParity(QSerialPort::NoParity);
else if (ui->comboUartParity->currentText() == tr("奇"))
member->serialPort->setParity(QSerialPort::EvenParity);
else
member->serialPort->setParity(QSerialPort::OddParity);
if (ui->comboUartStopBits->currentText() == "1")
member->serialPort->setStopBits(QSerialPort::OneStop);
else if (ui->comboUartStopBits->currentText() == "2")
member->serialPort->setStopBits(QSerialPort::TwoStop);
else
member->serialPort->setStopBits(QSerialPort::OneAndHalfStop);
member->serialPort->setFlowControl(QSerialPort::NoFlowControl);
connect(member->serialPort, SIGNAL(readyRead()), this, SLOT(on_uart_read()));
if (member->uart->open(QIODevice::ReadWrite))
{
// 打开成功
ui->buttonUartOpen->setEnabled(false);
ui->buttonUartClose->setEnabled(true);
}
else
{
// 打开失败
QMessageBox::critical(this, tr("错误"), tr("连接失败"), QMessageBox::Yes);
}
6.关闭串口
member->serialPort->close();
ui->buttonUartOpen->setEnabled(true);
ui->buttonUartClose->setEnabled(false);