QT += serialport
#include <QSerialPort>
private slots: //button void btn_open_port(bool); void btn_close_port(bool); void btn_send_data(bool); //receive data void receive_data();
/*-------------------------------------------------------- * functions * ------------------------------------------------------*/ void Serial::system_init() { //port config global_port.setParity(QSerialPort::NoParity); global_port.setDataBits(QSerialPort::Data8); global_port.setStopBits(QSerialPort::OneStop); //connect connect(ui->btn_open,&QPushButton::clicked,this,&Serial::btn_open_port); connect(ui->btn_close,&QPushButton::clicked,this,&Serial::btn_close_port); connect(ui->btn_send,&QPushButton::clicked,this,&Serial::btn_send_data); connect(&global_port,&QSerialPort::readyRead,this,&Serial::receive_data); }
其次,是slots,也就是编写槽函数,上例中的“//connect”里面列出了极为详细的 ui中的按键与槽函数的连接,分别编写每一个的槽函数。例如
void Serial::btn_open_port(bool) { ... } void Serial::btn_close_port(bool) { global_port.close(); ui->lab_status->setText("Disconnected"); } void Serial::btn_send_data(bool) { QString data = ui->lint_send_data->text(); QByteArray array = data.toLatin1();//QString->QByteArray global_port.write(array); } void Serial::receive_data() { QByteArray array = global_port.readAll(); qDebug()<<array; if(ui->checkBox->checkState() == Qt::Checked){ ui->plainTextEdit->insertPlainText(QString(array.toHex(‘ ‘).toUpper().append(‘ ‘))); }else{ ui->plainTextEdit->insertPlainText(QString(array)); } }
原文:https://www.cnblogs.com/KaiW/p/15111148.html