Hello, everyone. I’m Lao Wu.

Once again, I managed to write a small article. Whenever I was not motivated to write an article, I would lower the bar for writing an article. This is actually a good technique.

You’ve been reading some articles about agile development recently, or can you think about how to learn agile?

Working on a project for a long time can wear down a developer’s patience, and learning something for a long time can also SAP confidence.

Besides, how do you know if what you’re studying now will be useful in the future?

So, my conclusion is: apply what you learn as soon as possible. Can use a little is a little, not enough to go back to make up!

To get back to the subject, the best way to learn about Qt is to read the official manual and examples.

Today, I want to share the official example of Qt: Terminal.

A simple serial terminal tool:

Click to see a larger image

It demonstrates how to create a terminal and use QSerialPort for serial port communication.

Source file:

` terminal / ` ` ├ ─ ─ the console. The CPP ` ` ├ ─ ─ the console. H ` ` ├ ─ ─ images / ` ` ├ ─ ─ main. CPP ` ` ├ ─ ─ mainwindow. CPP ` ` ├ ─ ─ mainwindow. H ` ` ├ ─ ─ MainWindow. UI ' 'Heavy Exercises - - SettingsDialog.cpp' - - SettingsDialog.h ' 'Heavy Exercises - - SettingsDialog.ui' 'Heavy Exercises - - Terminal. pro' '└─ terminal.qrc`

Next, follow me to implement this gadget.

Table of Contents:

'1. Create Qt Widgets Application' 2. Design the main interface 3. Realize the functions of the main interface 4. Design the setting interface 5. Realize the setting interface function ' '6. Related Reference'

1. Create a new Qt Widgets Application

File > New File or Project > Applications > Qt Widgets Application > Choose:

Click to see a larger image

With QMainWindow as the base class, subclass named MainWindow:

After the creation is completed, you will get the following files:

` terminal / ` ` ├ ─ ─ main. CPP ` ` ├ ─ ─ mainwindow. CPP ` ` ├ ─ ─ mainwindow. H ` ` ├ ─ ─ mainwindow. UI ` ` ├ ─ ─ terminal. The pro ` ` └ ─ ─ terminal.qrc`

Operation effect:

Click to see a larger image

At this point, it only has the same interface as QMainWindow, without any functions related to the serial port terminal.

2. Design the main interface

The main interface is divided into four parts:

Click to see a larger image

1. Menu bar, implemented by QMenubar, is used to provide the core operation functions of the serial port terminal;

2. Toolbar, implemented with QToolbar, for providing shortcut operations;

3. Leave the middle field blank, which will be implemented later in C++ by inheriting QPlainTextEdit for input and output serial port information;

4. The status bar, implemented with QStatusBar, is used to display the current connection status.

In Qt Designer, do the following:

Add Calls and Tools to the menu bar:

Add the Connect and Disconnect submenu items to Calls to Connect and Disconnect the serial port, respectively.

In Tools, add sub menu items Configure and Clear to open the Settings window and Clear terminal information, respectively.

2. Add Connect, Disconnect, Configure and Clear buttons to the toolbar;

3. Add the Setting dialog box:

Using the Dialog without Buttions template, create a new Dialog box named “SettingsDialog”.

Operation effect:

Click to see a larger image

At this point, the menu bar and the menu items in the toolbar do not have any actual function.

3. Realize the Setting function

Since we need to set the parameters before connecting the serial port, we need to realize the function in the Setting interface first.

Design interface:

Click to see a larger image

At this point, there is no actual functionality.

Support to select serial port devices:

` / / file: settingsdialog. CPP ` ` void settingsdialog: : fillPortsInfo () ` ` {` `... ` ` / / to get the system the current list of all available serial port equipment ` ` const auto infos = QSerialPortInfo: : availablePorts (); For (const QSerialPortInfo & Info: infos) {' 'QStringList List; ` `description = info.description(); ` `manufacturer = info.manufacturer(); ` `serialNumber = info.serialNumber(); ` `list << info.portName(); ` `... ` `m_ui->serialPortInfoListBox->addItem(list.first(), list); ` ` `} ` `}

In Qt, we can use QSerialPortInfo to get a list of currently available SerialPort devices on the system. Once we get the SerialPort information, we use it to initialize the SerialPort combo box.

When selecting different serial port devices, the description information of the device should be switched:

`connect(m_ui->serialPortInfoListBox,` `QOverload<int>::of(&QComboBox::currentIndexChanged), this,&SettingsDialog::showPortInfo); `

Operation effect:

Click to see a larger image

Support setting serial port parameters:

` / / file: Settingsdialog. CPP ` ` void settingsdialog: : fillPortsParameters () ` ` {` ` / / add the optional baud rate, data bits, etc ` serial port parameters `m_ui->baudRateBox->addItem(QStringLiteral("9600"), QSerialPort::Baud9600); ` `m_ui->baudRateBox->addItem(QStringLiteral("19200"), QSerialPort::Baud19200); ` `m_ui->baudRateBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400); ` `m_ui->baudRateBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200); ` `... ` ` `}

In Qt, serialport related functions are implemented by the QTSerialPort module, as long as the QSerialPort and QSerialPortInfo classes.

Operation effect:

Click to see a larger image

Support save Settings:

CPP ' 'void settingsDialog ::apply()' '{'' updateSettings(); ` `hide(); ` `} ` ` / / to save a serial port parameters in variable m_currentSettings ` ` void SettingsDialog: : updateSettings () ` ` {` ` m_currentSettings. Name = m_ui->serialPortInfoListBox->currentText(); ` `m_currentSettings.baudRate = static_cast<QSerialPort::BaudRate>(m_ui->baudRateBox->itemData(m_ui->baudRateBox->currentIndex()).toInt()); ` `... ` ` `}

When the Apply button is clicked, Apply () is called, and the serial port parameters on the interface are saved in struct Settings m\ _CurrentSettings.

Operation effect:

Click to see a larger image

4. Realize the Connect function of serial port

` / / file: mainwindow.cpp` `void MainWindow::openSerialPort()` `{` `const SettingsDialog::Settings p = m_settings->settings(); ' '// Which serial device to open? ` `m_serial->setPortName(p.name); ` `... ' '/' 'is still the familiar open()' if (m_serial->open(qioDevice :: readWrite)) {' 'm_console->setEnabled(true); ` `m_ui->actionConnect->setEnabled(false); ` `m_ui->actionDisconnect->setEnabled(true); ` `m_ui->actionConfigure->setEnabled(false); ` `... ` ` `} ` `}

When the Connect button is clicked, the openSerialPort() is called, and the open() of QSerialPort is executed.

M \_console is an object of type QPlainTextEdit that is responsible for displaying the serial port.

Operation effect:

Click to see a larger image

At this point, the serial port device can be opened, but the serial port data cannot be displayed.

5. Realize the serial port reading and writing function

Support reading data from serial port:

'// file: MainWindow.cpp' 'void MainWindow::readData()' '{'' 'readData from the serial hardware' 'const QBytearArray data = m_Serial-> readAll(); ' '// Display in textbox' 'm_console->putData(data); ` ` `}

After opening the serial port, when the serial port has data, it calls MainWindow:: ReadData () to read out the data and display it on the interface. PutData () will be called

QPlainTextEdit: : insertPlainText () to display data in a text box.

Support for writing data to serial port:

` / / file: Console. CPP ' 'void console :: KeyPressEvent (QKeyEvent *e)' '{'' switch (e->key()) {' '// Do not handle certain key' cases Qt::Key_Backspace:` `... ` `break; ' 'Default:' ' '// Send the signal that received user input' emit getData(e->text().tolocal8bit ()); ` ` `} ` `}

When the user enters through the keyboard, m\_console catches the event and signals it, and when the main interface receives the signal, it performs the actual write serial operation:

'// File: MainWindow.cpp' 'MainWindow::MainWindow(QWidget *parent)' ':... ` ` {` `... ` `connect(m_console, &Console::getData, this, &MainWindow::writeData); ' ' '} ' 'void MainWindow::writeData(const QByteArray & Data)' '{'' '// familiar with write()' 'm_serial->write(data); ` ` `}

Operation effect:

Click to see a larger image

At this point, the core functionality of Qt’s official example subterminal is completed.

For those of you who are interested, please read the full code in Qt Example.

Relevant reference

Qt Official Document

  • https://doc.qt.io/qt-5/qtseri…

C++ GUI QT4 Programming (2nd Edition)

QT5 Introduction to Programming (2nd Edition)

Quick Start for Qt Creator

— The End —

Recommended reading:

Album | Linux driver development

Album | Linux system programming

Album | a little C every day

Album | Qt entry

Want to join a communication group?

Backstage reply [add group], I pull you into the group.