qt 主窗口对象串口通讯demo

mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>我是标题</string>
  </property>
  <property name="autoFillBackground">
   <bool>true</bool>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QWidget" name="layoutWidget">
    <property name="geometry">
     <rect>
      <x>50</x>
      <y>40</y>
      <width>661</width>
      <height>401</height>
     </rect>
    </property>
    <layout class="QVBoxLayout" name="verticalLayout">
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QComboBox" name="comboPort"/>
       </item>
       <item>
        <widget class="QPushButton" name="btnOpen">
         <property name="text">
          <string>打开串口</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="btnClose">
         <property name="text">
          <string>关闭串口</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
     <item>
      <widget class="QTextBrowser" name="textBrowser"/>
     </item>
    </layout>
   </widget>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

 mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <qserialport.h>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

signals:
    void customSinal();



private slots:
    void on_pushButton_clicked();
    void handleCosumSinal();

    void handleError(QSerialPort::SerialPortError error); // 错误处理
    void on_pushButton_2_clicked();
    void readSerialData();       // 读取串口数据
    void on_btnOpen_clicked();
    void on_btnClose_clicked();

private:
    Ui::MainWindow *ui;
    QSerialPort *serial;
    QSerialPort *serial2;// 串口对象
    void initSerialPort();       // 初始化串口
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "httpclient.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTextEdit>
#include <qpushbutton.h>
#include <qserialportinfo.h>
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow),serial(new QSerialPort(this)),serial2(new QSerialPort(this))
{
    ui->setupUi(this);

    // 初始化UI
    ui->btnClose->setEnabled(false);
    ui->textBrowser->setReadOnly(true);

    // 填充可用串口
    const auto ports = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &port : ports) {
        ui->comboPort->addItem(port.portName());
    }

    // 连接信号槽
    connect(serial, &QSerialPort::readyRead, this, &MainWindow::readSerialData);
    connect(serial, &QSerialPort::errorOccurred, this, &MainWindow::handleError);



}
MainWindow::~MainWindow()
{
    if (serial->isOpen()) serial->close();
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    connect(this,&MainWindow::customSinal,this,&MainWindow::handleCosumSinal);
    emit customSinal();
}

void MainWindow::handleCosumSinal()
{

}

void MainWindow::on_pushButton_2_clicked()
{
    QPushButton *pButton1 = new QPushButton("One");
    QPushButton *pButton2 = new QPushButton("Two");
    QPushButton *pButton3 = new QPushButton("Three");
    QPushButton *pButton4 = new QPushButton("Four");
    QPushButton *pButton5 = new QPushButton("Five");

    ui->horizontalLayout->addWidget(pButton1);
    ui->horizontalLayout->addWidget(pButton2);
    ui->horizontalLayout->addWidget(pButton3);
    ui->horizontalLayout->addWidget(pButton4);
    ui->horizontalLayout->addWidget(pButton5);
}


// 初始化串口参数
void MainWindow::initSerialPort()
{
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
}


// 读取串口数据
void MainWindow::readSerialData()
{
    QByteArray data = serial->readAll();  // 读取所有可用数据
    if (!data.isEmpty()) {
        // 转换为字符串显示(根据实际数据格式调整)
        QString message = QString::fromLatin1(data);
        // 假设ui是您的用户界面对象
        ui->textBrowser->document()->setMaximumBlockCount(10);
        ui->textBrowser->append("[接收] " + message.trimmed());
    }
}





// 错误处理
void MainWindow::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        QMessageBox::critical(this, "错误", "串口连接丢失: " + serial->errorString());
        on_btnClose_clicked();  // 自动关闭串口
    }
}

void MainWindow::on_btnOpen_clicked()
{
    if (ui->comboPort->currentText().isEmpty()) {
        QMessageBox::warning(this, "错误", "没有可用串口");
        return;
    }

    serial->setPortName(ui->comboPort->currentText());
    initSerialPort();

    if (serial->open(QIODevice::ReadWrite)) {
        ui->btnOpen->setEnabled(false);
        ui->btnClose->setEnabled(true);
        ui->textBrowser->append(">> 串口已打开: " + serial->portName());
    } else {
        QMessageBox::critical(this, "错误", "无法打开串口: " + serial->errorString());
    }
}

void MainWindow::on_btnClose_clicked()
{
    serial->close();
    ui->btnOpen->setEnabled(true);
    ui->btnClose->setEnabled(false);
    ui->textBrowser->append(">> 串口已关闭");
}

 

posted @ 2025-06-04 14:15  liliyou  阅读(12)  评论(0)    收藏  举报