• QT简单串口通信终端实现


    1.工程文件

    工程文件中添加serilport

    QT += serialport

    2.主程序

    主程序文件main.cpp

    #include "mainwindow.h"
    #include 
     
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
     
    
        return a.exec();
    }
     
    

    3.文本控制台类

    控制台类头文件console.h

    #ifndef CONSOLE_H
    #define CONSOLE_H
     
    
    #include 
     
    
    class Console : public QPlainTextEdit
    {
        Q_OBJECT
     
    
    signals:
        void getData(const QByteArray &data);
     
    
    public:
        explicit Console(QWidget *parent = nullptr);
     
    
        void putData(const QByteArray &data);
        void setLocalEchoEnabled(bool set);
     
    
    protected:
        void keyPressEvent(QKeyEvent *e) override;
        void mousePressEvent(QMouseEvent *e) override;
        void mouseDoubleClickEvent(QMouseEvent *e) override;
        void contextMenuEvent(QContextMenuEvent *e) override;
     
    
    private:
        bool m_localEchoEnabled = false;
    };
     
    
    #endif // CONSOLE_H
     
    

    控制台实现文件console.cpp 

    #include "console.h"
     
    
    #include 
     
    
    Console::Console(QWidget *parent) :
        QPlainTextEdit(parent)
    {
        document()->setMaximumBlockCount(100);
        QPalette p = palette();
        p.setColor(QPalette::Base, Qt::black);
        p.setColor(QPalette::Text, Qt::green);
        setPalette(p);
    }
     
    
    void Console::putData(const QByteArray &data)
    {
        insertPlainText(data);
     
    
        QScrollBar *bar = verticalScrollBar();
        bar->setValue(bar->maximum());
    }
     
    
    void Console::setLocalEchoEnabled(bool set)
    {
        m_localEchoEnabled = set;
    }
     
    
    void Console::keyPressEvent(QKeyEvent *e)
    {
        switch (e->key()) {
        case Qt::Key_Backspace:
        case Qt::Key_Left:
        case Qt::Key_Right:
        case Qt::Key_Up:
        case Qt::Key_Down:
            break;
        default:
            if (m_localEchoEnabled)
                QPlainTextEdit::keyPressEvent(e);
            emit getData(e->text().toLocal8Bit());
        }
    }
     
    
    void Console::mousePressEvent(QMouseEvent *e)
    {
        Q_UNUSED(e)
        setFocus();
    }
     
    
    void Console::mouseDoubleClickEvent(QMouseEvent *e)
    {
        Q_UNUSED(e)
    }
     
    
    void Console::contextMenuEvent(QContextMenuEvent *e)
    {
        Q_UNUSED(e)
    }
     
    

    4. 串口设置类

    串口设置类头文件settingdialog.h

    串口设置类实现文件settingdialog.cpp 

    5. 主窗口类

    主窗口类头文件mainwindow.h

    1. #ifndef MAINWINDOW_H
    2. #define MAINWINDOW_H
    3. #include
    4. #include
    5. QT_BEGIN_NAMESPACE
    6. class QLabel;
    7. namespace Ui {
    8. class MainWindow;
    9. }
    10. QT_END_NAMESPACE
    11. class Console;
    12. class SettingsDialog;
    13. class MainWindow : public QMainWindow
    14. {
    15. Q_OBJECT
    16. public:
    17. explicit MainWindow(QWidget *parent = nullptr);
    18. ~MainWindow();
    19. private slots:
    20. void openSerialPort();
    21. void closeSerialPort();
    22. void about();
    23. void writeData(const QByteArray &data);
    24. void readData();
    25. void handleError(QSerialPort::SerialPortError error);
    26. private:
    27. void initActionsConnections();
    28. private:
    29. void showStatusMessage(const QString &message);
    30. Ui::MainWindow *m_ui = nullptr;
    31. QLabel *m_status = nullptr;
    32. Console *m_console = nullptr;
    33. SettingsDialog *m_settings = nullptr;
    34. QSerialPort *m_serial = nullptr;
    35. };
    36. #endif // MAINWINDOW_H

    主窗口实现文件mainwindow.cpp 

    1. #include "mainwindow.h"
    2. #include "ui_mainwindow.h"
    3. #include "console.h"
    4. #include "settingsdialog.h"
    5. #include
    6. #include
    7. MainWindow::MainWindow(QWidget *parent) :
    8. QMainWindow(parent),
    9. m_ui(new Ui::MainWindow),
    10. m_status(new QLabel),
    11. m_console(new Console),
    12. m_settings(new SettingsDialog),
    13. m_serial(new QSerialPort(this))
    14. {
    15. m_ui->setupUi(this);
    16. setWindowTitle(tr("Serial Servo"));
    17. m_console->setEnabled(false);
    18. setCentralWidget(m_console);
    19. m_ui->actionConnect->setEnabled(true);
    20. m_ui->actionDisconnect->setEnabled(false);
    21. m_ui->actionQuit->setEnabled(true);
    22. m_ui->statusBar->addWidget(m_status);
    23. initActionsConnections();
    24. connect(m_serial, &QSerialPort::errorOccurred, this, &MainWindow::handleError);
    25. connect(m_serial, &QSerialPort::readyRead, this, &MainWindow::readData);
    26. connect(m_console, &Console::getData, this, &MainWindow::writeData);
    27. }
    28. MainWindow::~MainWindow()
    29. {
    30. delete m_ui;
    31. delete m_settings;
    32. }
    33. void MainWindow::openSerialPort()
    34. {
    35. const SettingsDialog::Settings p = m_settings->settings();
    36. m_serial->setPortName(p.name);
    37. m_serial->setBaudRate(p.baudRate);
    38. m_serial->setDataBits(p.dataBits);
    39. m_serial->setParity(p.parity);
    40. m_serial->setStopBits(p.stopBits);
    41. m_serial->setFlowControl(p.flowControl);
    42. if(m_serial->open(QIODevice::ReadWrite)){
    43. m_console->setEnabled(true);
    44. m_console->setLocalEchoEnabled(p.localEchoEnabled);
    45. m_ui->actionConnect->setEnabled(false);
    46. m_ui->actionDisconnect->setEnabled(true);
    47. m_ui->actionConfigure->setEnabled(false);
    48. showStatusMessage(tr("Connect to %1 :%2, %3, %4, %5, %6")
    49. .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
    50. .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));
    51. } else {
    52. QMessageBox::critical(this, tr("Error"), m_serial->errorString());
    53. showStatusMessage(tr("Open error"));
    54. }
    55. }
    56. void MainWindow::closeSerialPort()
    57. {
    58. if(m_serial->isOpen())
    59. {
    60. m_serial->close();
    61. }
    62. m_console->setEnabled(false);
    63. m_ui->actionConnect->setEnabled(true);
    64. m_ui->actionDisconnect->setEnabled(false);
    65. m_ui->actionConfigure->setEnabled(true);
    66. showStatusMessage(tr("Disconnected"));
    67. }
    68. void MainWindow::about()
    69. {
    70. QMessageBox::about(this, "About Serial Servo",
    71. tr("Serial Servo Demo"));
    72. }
    73. void MainWindow::writeData(const QByteArray &data)
    74. {
    75. m_serial->write(data);
    76. }
    77. void MainWindow::readData()
    78. {
    79. const QByteArray data = m_serial->readAll();
    80. m_console->putData(data);
    81. }
    82. void MainWindow::handleError(QSerialPort::SerialPortError error)
    83. {
    84. if(error == QSerialPort::ResourceError){
    85. QMessageBox::critical(this, tr("Critical Error"), m_serial->errorString());
    86. closeSerialPort();
    87. }
    88. }
    89. void MainWindow::initActionsConnections()
    90. {
    91. connect(m_ui->actionConnect, &QAction::triggered, this, &MainWindow::openSerialPort);
    92. connect(m_ui->actionDisconnect, &QAction::triggered, this, &MainWindow::closeSerialPort);
    93. connect(m_ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
    94. connect(m_ui->actionConfigure, &QAction::triggered, m_settings, &SettingsDialog::show);
    95. connect(m_ui->actionClear, &QAction::triggered, m_console, &Console::clear);
    96. connect(m_ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
    97. }
    98. void MainWindow::showStatusMessage(const QString &message)
    99. {
    100. m_status->setText(message);
    101. }

    6. 运行结果

  • 相关阅读:
    This download does NOT match an earlier download recorded in go.sum.
    系统测试UI测试总结与问题(面试)
    低代码平台:打破数据孤岛的利器,推动企业数字化转型
    《计算机基础与程序设计》之C语言复习—第二章算法
    k8s-20 hpa控制器
    整理 js 日期对象的详细功能,使用 js 日期对象获取具体日期、昨天、今天、明天、每月天数、时间戳等,以及常用的日期时间处理方法
    学习笔记1——SSM的基础知识
    path正则匹配MatcherUtil
    1859. 将句子排序
    电力智能运维管理平台:提升电力行业运营效率与安全
  • 原文地址:https://blog.csdn.net/zkmrobot/article/details/128117434