Hello, I’m Lao Wu.

I succeeded in writing another small article, and whenever I’m not motivated to write an article, I lower the threshold for writing an article. This is actually a good technique. Breaking a big goal into many smaller goals is a great way to combat procrastination.

Have you been reading some articles on Agile development, or are you thinking about how to learn agile?

Long hours on a project can wear out a developer’s patience, and learning something for a long time can also undermine confidence.

Besides, how do you know if what you are learning now will be useful in the future?

So here’s my conclusion: Try to use what you’ve learned right away. Can use a bit is a bit, not enough to use and then turn around to fill!

Getting back to business, the best way to learn Qt is to read the official manuals and examples.

The official example of Qt: Terminal.

A simple serial terminal tool:

Click for a larger version

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

Source code:

` terminal / ` ` ├ ─ ─ the console. The CPP ` ` ├ ─ ─ the console. H ` ` ├ ─ ─ images / ` ` ├ ─ ─ main. CPP ` ` ├ ─ ─ mainwindow. CPP ` ` ├ ─ ─ mainwindow. H ` ` ├ ─ ─ ├── ├.├.├.mainWindow.ui ├── ├.cpp ├── ├.ui ├── ├.io terminal.qrc`Copy the code

Next, follow me to implement this gadget.

Body contents:

Create a new Qt Widgets Application. Design the main interface 3. Realize the functions of the main interface 4. Design the setting interface 5. 6. Relevant referenceCopy the code

1. Create the Qt Widgets Application

In Qt Creator, click File > New File or Project > Applications > Qt Widgets Application > Choose:

Click for a larger version

Use QMainWindow as the base class and subclass named MainWindow:

You will get the following files:

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

Operation effect:

Click for a larger version

At this point, there is only the same interface as QMainWindow, and there is no serial terminal related functions.

2. Design the main interface

The main interface is divided into four parts:

Click for a larger version

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

2. Toolbar, implemented with QToolBar, for quick operation;

C++ inherits QPlainTextEdit to input and output serial port information.

4, status bar, with QstatusBar implementation, used to display the current connection status.

Perform the following operations in Qt Designer:

1. Add Calls and Tools menu items to menu bar:

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

Add Configure and Clear to Tools to open the Settings window and Clear terminal information, respectively.

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

3, Add the Setting dialog:

Create a new Dialog named “SettingsDialog” using the Dialog without Buttions template.

Operation effect:

Click for a larger version

At this point, menu items in the menu bar and toolbar have no actual function.

3. Implement the Setting function

As parameters need to be set before connecting the serial port, we need to implement the function in the Setting interface first.

Design interface:

Click for a larger version

At this point, there is no actual functionality.

Supports 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); ` ` `} ` `}Copy the code

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

When selecting a serial port device, change the device description:

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

Operation effect:

Click for a larger version

Supports 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); ` `... ` ` `}Copy the code

In Qt, serialport functions are implemented by the QtSerialPort module, as long as there are only two classes, QSerialPort and QSerialPortInfo.

Operation effect:

Click for a larger version

Support to save Settings:

'// file: settingsdialog.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()); ` `... ` ` `}Copy the code

When the Apply button is clicked, Apply () is called, saving the interface’s serial port parameters in struct Settings m_currentSettings.

Operation effect:

Click for a larger version

4. Implement the serial port Connect function

` / / file: mainwindow.cpp` `void MainWindow::openSerialPort()` `{` `const SettingsDialog::Settings p = m_settings->settings(); Which serial port device do you want to open? ` `m_serial->setPortName(p.name); ` `... 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); ` `... ` ` `} ` `}Copy the code

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

M_console is an object of type QPlainTextEdit, which is responsible for displaying serial ports.

Operation effect:

Click for a larger version

The serial port device can now be opened, but the serial port data cannot be displayed.

5. Implement the serial port read and write function

Supports reading data from serial ports:

// File: mainwindow.cpp ' 'void mainwindow ::readData() {const QByteArray data = m_serial->readAll(); M_console ->putData(data); ` ` `}Copy the code

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

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

Supports writing data to serial ports:

` / / file: Console. CPP ' 'void console ::keyPressEvent(QKeyEvent *e)' '{switch (e->key()) {'' // do not handle some key cases Qt::Key_Backspace:` `... ` `break; Emit getData(e->text().tolocal8bit ()); ` ` `} ` `}Copy the code

When the user enters through the keyboard, m_Console will catch the event and send a signal. When the signal is received by the main interface, the real write serial operation will be performed:

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

Operation effect:

Click for a larger version

This completes the core functionality of Qt’s official example sub-terminal.

Read the full Qt Example code for yourself.

Relevant reference

Qt Official Documentation

  • Doc. Qt. IO/qt – 5 / qtseri…

C++ GUI Qt4 programming (second edition)

Introduction to Qt5 Programming (Second Edition)

Qt Creator Quick Start

— 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 networking group?

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