C++ QT(1)

First introduction to Qt

This chapter will introduce what Qt is and work with you to install Qt. According to the programming habits of different users, here we will introduce the installation under Windows and Ubuntu. The tutorial focuses on writing Qt in the Ubuntu environment. Configure the Chinese input method of Qt Creator under Ubuntu and explain the interface composition and settings of Qt Creator. Create a simple "Hello world" routine to teach everyone the steps to create, compile and debug Qt applications.
We focus on section 3.4, building the Qt development environment under Linux, because building the environment is a critical step. Some friends may get stuck in the step of setting up the environment and cannot proceed. There is still a long way to go in subsequent development. Therefore, we need to be patient enough, not impetuous, follow the steps of the tutorial carefully, and learn to adapt and find solutions when encountering errors. If you are not familiar with using Ubuntu, it is recommended to practice more.

What is Qt

Qt is a cross-platform C++ development library. It is mainly used to develop Graphical User Interface (GUI) programs.
Although Qt is often regarded as a GUI library for developing graphical interface applications, this is not all of Qt;
in addition to drawing beautiful interfaces (including controls, layout, and interaction), Qt also includes many other functions, such as multi-threading , database access, image processing, audio and video processing, network communication, file operations, etc., these are all built-in in Qt.
Qt also has bindings for scripting languages ​​such as Python, Ruby, and Perl, which means that Qt-based programs can be developed using scripting languages. This is what the open source community is like. Good things will be derived and expanded, used everywhere, and become stronger and stronger.
Qt supports many operating systems, such as general operating systems Windows, Linux, and Unix, smart phone systems Android, iOS, and WinPhone, embedded systems QNX, VxWorks, and so on.
To put it simply, Qt can do a lot of things. For example, many software under Windows are developed by Qt. One of the features I like very much is that it can be used across platforms. "Cross-platform" means that a code can be used without any modification or It can run on other platforms with minor modifications.
The author will no longer introduce the development history of Qt, which can be found online. It feels useless to write too much. Anyway, Qt is a good tool for you to choose when making interfaces!

What Qt can do

What can Qt do? Theoretically speaking, Qt can basically do all the apps you can think of. Large desktop applications such as WPS, Maya (3D modeling), and the cores of some games can be implemented using Qt. You can even quickly use Qt to develop a music player like Kugou and NetEase Cloud Music. In the embedded world, using Qt to develop interfaces has become an irreplaceable trend. Industrial control interfaces are the most commonly used, and some mobile interfaces have also begun to use Qt. Such as ordering machines, temperature collection data display,
car instruments, speed display interface, etc. Qt can make beautiful interfaces, so QML (a descriptive language) was launched. Every Qt update optimizes or adds features to Quick (the module used by QML). It seems that Qt plans to enter the mobile device development market! Haha, in fact Qt has already been developed in this area!
Below are some small examples of interfaces developed in this book, please enjoy them. The key to developing a good interface is to have ideas. It can be said that if you are making an interface, you actually spend most of your time beautifying the interface, and the functions are relatively easy to implement. It is best for readers to have a certain art foundation, such as basic PS, so that they do not need to bother the company's artists during the development process. The interface and program can be developed together.
Dark theme music player interface UI design.
Insert image description here
Simple video interface design.
Insert image description here
Cool car music APP main interface development.
Insert image description here
These designs are all in Chapter 12 Multimedia Chapter and Project Practice Chapter in the second improvement chapter. The author's skills are limited, but I love designing UI and try my best to make the UI beautiful and practical. At least it's better designed than other Qt books. Qt design should have put more effort into the interface, and the functions are not difficult to implement. In the future, you will find that designing the interface may take up 70% of the time, and writing programs may account for 30%. Everyone should put more effort into designing the interface! ! !

Qt/C++ and QML

QML is an extension of Qt C++. In other words, basically all interface classes used in Qt C++ can be extended to QML. If it cannot be expanded, you can also use QML directly with C++. Qt C++ is actually more efficient. Therefore, this tutorial is an introductory tutorial based on Qt C++. QML can be said to be a plus. The Qt QML module provides a framework for developing applications and libraries in the QML language. QML itself does not involve the display part, so the Qt Quick module plays the role of this part. As for the relationship between the three of them, we can just briefly understand it.
Qt C++ has more prominent writing functions at the bottom level. If you want to have a good-looking interface and powerful functions, the combination of Qt C++ and QML language is essential. The QML language is responsible for the interface layer, while the bottom layer calls Qt C++. For example, file reading and writing, image processing, multi-threaded communication, etc. all need to be written in C++.
At present, Qt C++ is more mature, and QML is also relatively mature at present, because QML is also updated every time the version is updated.
However, QML is not mature enough in lower versions of Qt (such as Qt5.6 or below), while QML is more mature in higher versions of Qt (such as Qt5.7 or above). C++ is still the main programming language of Qt, and Qt 5 has not ignored it. Qt 5 has added many new C++ APIs and will continue to be updated. The introduction of QML should be a breakthrough for Qt into the mobile market, and both python and javascript can be used in Qt.
I talked about C++ and QML, but the Qt basic tutorial still focuses on Qt C++. It is not difficult to learn other things in Qt with the basics!

How to choose Qt version

How should beginners choose the version of Qt? The latest Qt5 version as of 2020 is Qt5.15. You can refer to this URL https://doc.qt.io/qt-5/qt5-intro.html to see the update instructions for each Qt version. Qt6 has been released. Is it necessary for us to directly install the latest version of Qt6? No! Qt6 is theoretically compatible with Qt5, but many companies are using Qt5 or even Qt4. After learning about Qt5, Qt6 and other stable versions are released, and when they are widely used in the market, it is the wisest choice for us to use Qt6. It often takes a certain amount of time to adapt to new things! We mainly briefly explain the entire Qt version. First of all, the upgrade of the Qt version must be an optimization of the previous version. For example, there are differences in the syntax between Qt4 and Qt5, and the way of writing signals and slots in Qt5 is different from the way of writing signals and slots in Qt4. In addition to Qt5.10 and above, Qt5.6 and Qt5.9 are Qt long-term supported versions LTS (Long
Term Support, referred to as LTS). However, in March 2020, Qt officially archived Q5.2~Qt5.8 and Qt5.11 to http://download.qt.io/new_archive/qt/. Therefore, many friends who want to use the old version of Qt should go to the link above to download it. After all, sometimes our development board programs are developed under a certain Qt version. If we want to migrate to a new version of Qt, we may have to consider compatibility issues! But it won't change much, don't worry!
Insert image description here
The official Qt download link is posted below http://download.qt.io/archive/qt/. We go directly to this link to see the picture below. The picture below and the picture above add up to the complete version of Qt. There are so many versions to choose from. You can also see that the Qt version is constantly being updated, and more functions will be injected into the Qt GUI library, making our development easier and more interesting! The era of Qt6 is coming!
Theoretically, the newer the version of Qt we choose, the better. This is of course, but we still have to make sure a version is necessary, because the programs written in the future must run in a certain version for a long time to avoid random upgrades that will bring other problems. Compatibility issues, or repeated porting and other work. Qt will continue to be updated. Qt5.9 and Qt5.12 are two long-term supported versions of LTS. This tutorial uses the Qt5.12.9 version for development and experimental instructions.
Insert image description here

Install Qt under Windows

In the previous section, we already knew the download address of Qt. Download as follows on Windows. Enter the address. This section only introduces Qt installation under Windows.
Enter http://download.qt.io/archive/qt/5.12/5.12.9/, (note that if the download link cannot be found, we will search the top-level directories of http://download.qt.io one by one. , because the Qt download link will change). Select the ninth version of Qt5.12 from Qt5.12 version. “.dmg” is the installation package of the Mac system version, and there is no installation explanation here. The figure below shows the installation package format under Windows and Linux.
Insert image description here
Right-click the mouse to select the Winodws download installation package and choose to use Thunder to download. If Thunder is not installed, just click on the link to download. The download speed may be slow. Use Thunder to download, the speed will be faster.
Insert image description here

After the download is completed, find the installation package file and double-click the installation package file. start installation.
Insert image description here

The installation interface will pop up, click Next.
Insert image description here
Log in to your Qt account. If you don't have an account and password yet, please go to https://www.qt.io/ to register one yourself.
Insert image description here
Qt installer, the open source version of Qt follows the GPLv 2, GPL v3 or LGPL v3 license. Check the box to agree to use the open source version of Qt and fill in your company/individual name.
Insert image description here

Qt's welcome installation interface
Insert image description here
. Modify the installation directory
Insert image description here
and select the components that need to be installed. The components that Windows chooses to install are as follows. MSVC is Microsoft's VC compiler and requires the installation of VC related libraries before it can be used. MinGW is the abbreviation of Minimalist GNU on Windows, which allows you to generate native Windows programs on GNU/Linux and Windows platforms without the need for a third-party C runtime library. In addition to the Android option arm and other options, we only need to check the MinGW option. Sources is the Qt source code. Source The following are some modules of Qt. You can choose to install or not. Here we choose full outfit.
Insert image description here
Select to agree to the license agreement and click Next.
Insert image description here
Click Next.
Insert image description here
When preparing to install Qt, you can see that the more components we install, the larger the installation space will be. Close to 10G.
Insert image description here
Qt is being installed.
Insert image description here
When the installation is complete, check Start Qt Creator and click Finish.
Insert image description here
After the installation is completed, the interface of opening Qt Creator is as follows.
Insert image description here

Install Qt under Linux

Install Qt

Similarly, enter the http://download.qt.io/archive/qt/5.12/5.12.9/ download page (note that if the download link cannot be found, we will go to the top-level directory http://download.qt.io Search each directory, because the Qt download link will change), select the Linux installation package to download. Use Thunder to download and copy to the Ubuntu virtual machine or directly copy the link address to the Ubuntu virtual machine for download.
Insert image description here

As shown in the figure below, copy the link download address to the Ubuntu virtual machine terminal and use the command wget to download, http://download.qt.io/archive/qt/5.12/5.12.9/qt-opensource-linux-x64-5.12.9. run.

wget http://download.qt.io/archive/qt/5.12/5.12.9/qt-opensource-linux-x64-5.12.9.run

Insert image description here

Grant executable permissions and add sudo permissions to enter the installation, which will install it in the /opt directory.

chmod +x qt-opensource-linux-x64-5.12.9.run
sudo ./qt-opensource-linux-x64-5.12.9.run

Insert image description here
After executing the installation instructions, the Qt installation interface will pop up, which is the same as the Qt installation steps under Windows. Please refer to Section 3.3. When selecting the installation directory, the default installation directory will suffice. Installation component selection is as follows.
Insert image description here
After the installation is complete, find Qt Creator in the application center in the lower left corner and click to open Qt Creator.
Insert image description here

The interface for opening Qt Creator is as follows, and the installation is complete.
Insert image description here

Configure Qt Creator to input Chinese

Configure Ubuntu Chinese environment

The default installation environment of Ubuntu uses English, which many students are not used to. Now we set Ubuntu's system language to Chinese. In the upper right corner of Ubuntu, click the settings icon in step 1 as shown below.
Insert image description here

Set as shown below, click (install/Remove Languages...) to install or remove languages, select Simplified Chinese in the installation language, and click Apply.
Insert image description here
Insert image description here
After the configuration is completed, click Restart (or log out of Ubuntu). After restarting, because we have updated the system language, Ubuntu asks us if we need to change the name of the system folder to Chinese. Here the author chooses No and keeps the old name.
There are some advantages to retaining the old names, that is, when we enter these access directories, we can directly use English without switching to the Chinese input method. Strictly speaking, it is best to develop in an English environment. This is for beginners or those who are forced to speak Chinese, so we need to configure the Chinese environment here, and later develop Qt and need to write Chinese comments to facilitate understanding and show to future generations.
Insert image description here

Configure Chinese input method

We have configured the Chinese environment above and have the pinyin input method ibus, but ibus is not easy to use. Qt Creator does not support ibus input for Chinese. Good production tools determine good productivity. Let's introduce the Fcitx input method.
Fcitx (Flexible Input Method Framework) ── Little Penguin Input Method, which is an input method platform released under the GPL, can support multiple input methods through the installation engine, and supports simple input and complex output. It is commonly used in the Linux operating system Chinese input method. Its advantages are: short and concise, and better compatibility with programs.
The built-in input method of Fcitx supports Chinese Pinyin and character table-based input (such as Wubi). Depending on the language, there are different input method engines to choose from.
Among the Pinyin input methods supported by Fcitx, the built-in Pinyin has the fastest response speed. Fcitx also supports popular third-party pinyin input methods to provide better sentence input.
fcitx-sunpinyin has a good balance between input speed and input accuracy.
The fcitx-libpinyin algorithm is more advanced than sunpinyin.
fcitx-rime, the Fcitx version of the famous Chinese input method Rime IME. But it does not support Fcitx’s own #special symbols and #quick input functions. For custom settings, please see the official website (http://rime.im/).
fcitx-googlepinyin, Google Pinyin input method for Android. fcitx-sogoupinyin (AUR,) Sogou input method for linux—supports full pinyin, simplified pinyin, fuzzy sound, cloud input, skin, Chinese-English mixed input. Official website (http://pinyin.sogou.com/linux/).
fcitx-cloudpinyin can provide support for cloud pinyin input and supports all pinyin input methods under Fcitx, except Fcitx-rime.
fcitx-chewing adds chewing (Traditional Chinese phonetic notation) input engine support to Fcitx. Depends on libchewing.
fcitx-table-extra adds Cangjie, Zhengma, Boshiamy support.
Install Fcitx input method. The following mainly introduces two input methods (Wubi input method and Pinyin input). This time, we take the installation of Wubi input method as an example.

sudo apt-get install fcitx-table-wubi // 五笔输入法
sudo apt-get install fcitx-sunpinyin // 拼音输入法请装sunpinyin 或者fcitx-googlepinyin

Go to the upper right corner and click System Settings, find Language Support, click the drop-down checkbox of the keyboard input method system to select fcitx, then click Apply to the entire system, and then close it. The steps are as shown below.
Insert image description here
In order to ensure that the newly configured environment takes effect, restart the Ubuntu system after completing the above steps.
Follow the steps below. In the pop-up "Input Method Configuration" dialog box, if the Wubi glyph input method does not appear, click the "+" button in the lower left corner to add the Wubi glyph to the input method list, and then click " ^" will add the Wubi font to the top.
Insert image description here
Open Qt Creator, "Show Applications" in the lower left corner, find the Qt Creator icon and click to open Qt Creator.
Insert image description here
At this time, the input method mark in the upper right corner is still the English input method, and Chinese input cannot be entered at ④. Pressing Ctrl+Shift cannot switch to the Chinese input method state.
Insert image description here

In order to solve the problem that Linux Qt Creator cannot input Chinese, the author has compiled the fcitx plug-in and uploaded it to the Gitee warehouse. You can download it and use it directly.
If you do not have Git installed, please install Git first using the instructions below.

sudo apt-get install git

Use the following instructions to download the Qt Creator plug-in. This plug-in supports Qt5. Qt4 has not been tested. This plug-in was tested on Qt5.5.1, and later the Qt version was upgraded to Qt5.12.9. The installation directory plug-in paths of the two Qt versions Qt5.5.1 and Qt5.12.9 have changed (it means that the versions are very different and the installation paths have changed). The plug-in downloaded from Gitee is suitable for Qt5.12 or so. If you use other versions, please modify the installation path in the fcitx-install.sh script yourself!

git clone https://gitee.com/QQ1252699831/fcitx-qt5-1.1.1.git
cd fcitx-qt5-1.1.1

Insert image description here
Directly execute the script installation. The principle is to copy the plug-ins in the fcitx-qt5-1.1.1 folder to the Qt Creator installation directory. Please note that the path of Qt Creator installed personally must be the same as the path installed by the author, otherwise you need to modify the path in the fcitx-install.sh script yourself!

./fcitx-install.sh

Insert image description here
At this point, reopen Qt Creator before you can enter Chinese! As shown below. You need to press Ctrl+Space (space bar) to activate the input method, and then press Ctrl+Shfit to switch the input method to Wubi input method.
Insert image description here

Qt Creator is easy to use

Qt Creator interface composition

After starting Qt Creator, the main interface of Qt Creator is as shown below. The welcome page is opened by default. You can see that Qt Creator comes with many examples. In Ubuntu, since Qt Creator is installed in the /opt directory, ordinary users do not have permission to write to this directory and can only read it. If you want to open the example, click and then select "Copy project and open". The author prefers the interface design of Qt Creator. It’s very concise and comes with examples, so you can refer to it even if you don’t know how to write! The most important thing is the "
Help . There are many instructions for use and the summary is very good. It is very helpful for learning Qt classes. If you learn a certain method or class and you don't know how to use it, you can Open this Help to search for usage of this class or method. No tutorial can be as detailed as the Qt help document. Unfortunately, it is in English, so it will still be difficult for beginners to learn. Please refer to this Qt help document, because you can learn a lot there, and there are many examples and explanations. Each method, class, signal, slot, etc. has a detailed explanation.
Insert image description here
Click the "Help" menu on the top toolbar, click "UI Tour" and instructions introducing each component of Qt Creator will appear.
Everyone must read this. Although the explanation is in English, you can generally understand it. No more screenshots will be given here. Writing the first Qt program later will also explain the process of writing, compiling and running the entire project. We only need to know so much about interface composition.
Insert image description here

Qt Creator settings

The settings in Qt Creator are more important. What can we do in the settings of Qt Creator? We usually set the font size, color, background color, etc. so that it looks more dazzling or more in line with our own style. There are also many themes in Qt Creator, with many combinations. I believe there is one you like. If you don't like it, you can customize the font size, color, background color, etc. Click "Tools" > "Options" on the top menu bar.

Insert image description here
After opening the option, you can see the interface as shown below.
Insert image description here
Below we mainly introduce some commonly used ones:

  1. Kits: Mainly shows compilation tools. When we installed Qt Creator on Ubuntu, the Desktop Qt5.12.9 GCC 64bit option was already checked in the installation options. Therefore, the installed compilation tools can be detected on the Kits page.
    You can also view Qt Versions and other items freely. The important thing is that we can configure the compilation tools of the ARM platform in this Kit (how to configure it will be discussed later when using an ARM board platform as a tutorial). The reason why Qt can be cross-platform is because Qt has compilation tools for different platforms. .
  2. Environment: Different themes and languages ​​can be set in this item. Qt Creator's default theme and system language are sufficient.
  3. Text editor: You can set the font size, color, etc. of the text editor. You can also set the font color for certain types of text, such as keywords, strings, and comments.
  4. Build and run: Commonly used is to set the project directory. Others generally do not need to be modified, the default is enough.

The first Qt program

The origin of "hello world" dates back to 1972, when Brian Kernighan, a famous researcher at Bell Labs, first used it (program) when writing "Tutorial Introduction to the Language B". This is the earliest known program. Records of hello and world being used together in computer writings. The first program always uses "hello, world" as the default first program. Let's continue this classic approach and feel the greatness of the program. At the same time, it can give us a preliminary understanding of the basic process of Qt project construction.

Create a new project

Open Qt Creator in Ubuntu18, that is, after clicking on the software center in the lower left corner, find the icon of Qt Creator and click to open it. Click on the file Qt Creator's file and choose to create a new file or project. Note that there is a shortcut key Ctrl + N. You can also quickly open a new project by directly using "Ctrl + N" in the activated state of Qt Creator and the input method in the English state.
Insert image description here
The new project that pops up is as shown below. Here we can see that there are many templates (including project templates and file and class templates) that can be used, including Qt, Qt Quick, Qt for Python,..., C++ and so on. As a beginner, we choose the first Application (Qt) and Qt Widgets Application. The so-called template is Qt. In order to facilitate the development of programs, when creating a new project, users can write programs based on a template, including cpp files and ui files. Quick creation without the user having to manually create these files. This brings great convenience to user development. Of course, users can manually create projects by themselves, and it is also possible to add them one by one. But beginners are not recommended to do this. Our purpose is to experience the process of project construction first, and then go back and try to do it yourself when you have time in the future!
Insert image description here
If your input method is currently in the Chinese input method, first press Ctrl and then Space (space) to switch to the English input method. Enter the project as "01_hello_world" in the name. The project path here is Qt under the author's personal home directory path. Directory, check Set as default project path, so that when doing project experiments in the future, this directory will be selected as the project path by default instead of manually selecting the path. Select Next.
Insert image description here
The default is to choose qmake to compile, mainly use qmake to generate Makefile for project compilation. Just click Next.
Insert image description here

The base class selected by default here is QMainWindow. In the Base class item, we can also see that there are base classes such as QWidget and QWialog to choose from. In the C++ chapter, we have already learned what a base class is. To put it simply, the project we created is developed based on the QMainWindow class. "Generate form" is checked by default, which means to generate the ui form file mainwindow.ui. For the convenience of learning, we uniformly default the base class to QMainWindow, but note that in embedded applications,
title bars, status bars, etc. are generally not needed, so the QWidget base class is commonly used.
QMainWindow: Main window class. The main window has the main menu bar, toolbar and status bar. Similar to the main window of a general application. If you want to develop software for nested window programs, you might as well choose QMainWindow.
QWidget: It is the base class of the visual interface class, which means that the QMainWindow class is also inherited and encapsulated from QWidget. So QWidget has fewer functions than QMainWindow.
QDialog: Dialog class, build a dialog interface. This is less commonly used as a base class. Generally, QMainWindow and QWidget are used as base classes. Note: Because QWidget does not have a window title bar, etc., it is best to use QWidget embedded.
Insert image description here

In higher versions of Qt Creator, there is a Translation item. Qt provides you with a (.ts) file. .ts is a readable translation file using a simple XML format. For the time being, we only need to know that this thing is a readable translation file. Rarely needed. Click Next.
Insert image description here
Check the compiler. This compiler is what we selected when installing the component. Using this compiler, we can compile an executable program that runs on the Ubuntu version. With that said, do you think it is possible to compile executable programs for other platforms? That's right, if we now have the Qt compiler for the ARM platform, then choosing the Qt compiler for the ARM platform can compile the Qt executable file on the ARM platform (the executable file mentioned here is similar to the exe program file of the window, can be run directly). Click Next.
Insert image description here

At this point, Qt Creator asks whether to use version control. If you have learned a version control tool like Git, you can choose Git to use version control for your project. The default selection is no version control, just click Finish.
Insert image description here

The newly created "01_hello_world" project is as follows.
Insert image description here

Project document introduction

Among them, there are two sub-windows on the left side. The upper window displays the file structure of the project, showing that the current project is "01_hello_world". If you are careful, you will also find that "01_hello_world" is marked in bold black. Indicates that this project is an active project, and the project root nodes of active projects are all indicated in bold font. If multiple projects are opened, then we only need to observe which one is the bold project name to indicate the current active project.
Qt Creator is the same as other IDE development software. They all manage various source files in the project in groups. The following is a brief introduction to the files in the project.
01_hello_world.pro is a project management file. This project management file is very important. When you add a file or delete a file, Qt Creator will automatically modify this *.pro file. Sometimes we need to open this *.pro file to add our
setting items.
Header grouping, all the header files *.h in the project are stored under this node.
Source group, all C++ source code files *.cpp in the project are stored under this node.
Forms group, under this node is to store all interface files *.ui in the project. The *.ui file is composed of XML language description, and
the corresponding cpp file will be generated when compiling, so that the cross compiler can compile it.

Project file*.pro

The 01_hello_world.pro file is shown below. This pro file has some differences between high version Qt and low version Qt files, and the pro generated under Windows and Linux systems are also somewhat different, but the changes are not significant.

01_hello_world.pro文件内容
1 QT += core gui
2
3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
4
5 CONFIG += c++11
6
7 # The following define makes your compiler emit warnings if you use
8 # any Qt feature that has been marked deprecated (the exact warnings
9 # depend on your compiler). Please consult the documentation of the
10 # deprecated API in order to know how to port your code away from it.
11 DEFINES += QT_DEPRECATED_WARNINGS
12
13 # You can also make your code fail to compile if it uses deprecated APIs.
14 # In order to do so, uncomment the following line.
15 # You can also select to disable deprecated APIs only up to a certain
version of Qt.
16 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the
APIs deprecated before Qt 6.0.0
17
18 SOURCES += \
19 main.cpp \
20 mainwindow.cpp
21
22 HEADERS += \
23 mainwindow.h
24
25 FORMS += \
26 mainwindow.ui
27
28 # Default rules for deployment.
29 qnx: target.path = /tmp/$${
    
    TARGET}/bin
30 else: unix:!android: target.path = /opt/$${
    
    TARGET}/bin
31 !isEmpty(target.path): INSTALLS += target

Line 1 adds modules supported by Qt. The core and gui libraries are Qt's default settings.
Line 3 compares the Qt5 version. If it is the Qt5 version, the application in main.cpp is in QtWidgets, so this library must be included.
Lines 5 and 11 configure using c++11 and adding QT_DEPRECATED_WARNINGS definition respectively.
Line 18, under SOURCES is the source file.
Line 22, under HEADERS is the header file.
Line 25, under FORMS is the ui interface file.
Line 28 deploys the default rules.
Line 29, qnx: Determine whether it is a qnx operating system and assign target.path = /temp/ TARGET/bin. Line 30, if it is a unix system but not Android, assign target . path = / opt / {TARGET}/bin. Line 30, if it is a unix system but not Android, assign target.path = /opt/T A RGET / bin . Line 30 , if it is a Unix system but not Android, assign the value t a r g e t . p a t h=/ o pt / {TARGET}/bin.
Line 31, if target.path is an empty directory, assign INSTALLS += target.
If you need to modify the executable program name of the generated target, you can assign TARGET = xxx. Otherwise TARGET will default to the name of the project.

Style file *.ui

mainwindow.ui is an xml type file, and its xml content is as follows. This file is generated and cannot be edited manually. Its properties can only be modified through the graphical interface.

1 <?xml version="1.0" encoding="UTF-8"?>
2 <ui version="4.0">
3 <class>MainWindow</class>
4 <widget class="QMainWindow" name="MainWindow">
5 <property name="geometry">
6 <rect>
7 <x>0</x>
8 <y>0</y>
9 <width>800</width>
10 <height>600</height>
11 </rect>
12 </property>
13 <property name="windowTitle">
14 <string>MainWindow</string>
15 </property>
16 <widget class="QWidget" name="centralwidget"/>
17 <widget class="QMenuBar" name="menubar">
18 <property name="geometry">
19 <rect>
20 <x>0</x>
21 <y>0</y>
22 <width>800</width>
23 <height>28</height>
24 </rect>
25 </property>
26 </widget>
27 <widget class="QStatusBar" name="statusbar"/>
28 </widget>
29 <resources/>
30 <connections/>
31 </ui

Double-click mainwindow.ui to jump to the design interface, as shown below. The following mainly introduces the main part.
Insert image description here

  1. ① is the control bar, which has various controls. The Filter above is the filter. By entering the initial letters, we can quickly find the control we are looking for.
  2. ② What is displayed is our window program, which already has the MainWindow object and several sub-objects. By default, MainWindow has a menu bar and status bar.
  3. ③ is the object bar, and the objects used in ② are displayed in ③.
  4. ④ is the property bar. Click on an object in the object bar at ③ to edit its properties in ④. There are many attribute items, including position, size, text, color, font, etc.

Header file *.h

Click Edit in the left column to return to the project editing work window. Click mainwindow.h under Headers under the project. Mainwindow.h usually has a corresponding cpp file called mianwindow.cpp. Among them, mainwindow.h contains the declaration of the class, and mainwindow.cpp contains the implementation of the class. This is the same as the C++ we learned earlier. The contents of mainwindow.h are as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5
6 QT_BEGIN_NAMESPACE
7 namespace Ui {
    
     class MainWindow; }
8 QT_END_NAMESPACE
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19 Ui::MainWindow * ui;
	20
};
21 # endif /* MAINWINDOW_ */

Line 7 defines the namespace Ui, which contains a class MainWindow. This MainWindow is not the same object as the MainWindow in line 10. In fact, the MainWindow class in this file has a member *ui, which is the pointer to Ui::MainWindow on line 19. This is all for designing the interface using .ui files.
Line 12, the first line in the declaration of MainWindow is Q_OBJECT, which is a macro, which is processed by Qt. This is where Qt expands for C++. All classes that use signals must add this macro.

Source file *.cpp

Click mainwindow.cpp under Sources under the project. Its contents can be seen as follows.

1 # include "mainwindow.h"
2 # include "ui_mainwindow.h"
3
4 MainWindow::MainWindow( QWidget *parent )
5 : QMainWindow( parent )
	6, ui( new Ui::MainWindow )
	7
{
    
    
	8 ui->setupUi( this );
	9
}


10
11 MainWindow::~MainWindow()
12
{
    
    
	13 delete ui;
	14
}

Line 2, in the MainWindow implementation class, includes a file ui_mainwindow.h. This file is automatically generated by Qt based on the .ui file. That is to say, ui_mainwindow.h must be generated after clicking Build before we can see it. this file. This file can be found in the debug/release directory after building/compiling.
Line 6, separated by "," in the MainWindow constructor, create a new MainWindow in Ui. Here is a way to initialize members.
Line 8, ui->setupUi(this); This sentence is to initialize the interface. Pass this (referring to the MainWindow class itself) as a parameter to setupUi. The object of the ui interface file will have this as the parent object. , all sub-objects will be displayed in MainWindow. If we want to use the objects in ui, we must write the code after the sentence ui->setupUi(this), because ui->setupUi(this) will first initialize the objects inside, and we can only use this after initializing the objects inside. object.
On line 13, delete ui in the destructor. In Qt, the object we need to delete in the destructor is usually an object created by new and has no parent object.

Tip: this is constructed before the execution of the member function starts, and is cleared after the execution of the member ends.

Click main.cpp under Sources under the project. Its contents can be seen as follows.

1 # include "mainwindow.h"
2
3 # include < QApplication >
4
5 int main( int argc, char *argv[] )
6
{
    
    
	7 QApplication a( argc, argv );
	8 MainWindow w;
	9 w.show();
	10 return(a.exec() );
	11
}

Line 3 contains the definition of the QApplication class. A QApplication object must be used in every application using Qt. QApplication manages a wide range of resources for a variety of applications, such as default fonts and cursors.
Line 5, main() function is the entry point of the program. In almost all cases of using Qt, main() only needs to perform some initialization before passing control to the Qt library, which then uses events to inform the program of the user's actions. argc is the number of command line variables and argv is an array of command line variables.
Line 7, a is the QApplication of this program. It is created here and handles these command line variables.
Line 8 creates an object w, which is MainWindow.
Line 9, calls the method show(). Only in this way can the program interface be displayed.
Line 10, here is main() transferring control to Qt, and exec() will return when the application exits.
In exec(), Qt accepts and processes user and system events and passes them to the appropriate widgets.

Modify the ui file to display hello world

Double-click mainwindow.ui to enter the "Ui Designer" page as shown below.
Insert image description here
You can see that the main form to be designed in the middle is currently empty, but there are already several members on the form. You can see the object bar on the right, and there are already 3 object members in it, but we can't see it. That's it, the effect is not very obvious.
If we want to display "Hello World!" in the form, we need to use the control bar on the left. Currently, there are many controls in the control bar on the left, and they are divided into many categories. For us beginners, we don’t need to know how to use them for the time being. The categories in the following tutorials explain how they are used. Now we mainly want to display "Hello World!". To understand our main purpose, don’t look at the control bar on the left and want to try them one by one without knowing how to use them. This way of learning is wrong. To display "Hello World!", then we need to use a commonly used text display control. The commonly used one is the Label text control. Of course, the PushButon button class can also display text. But we don't need the functionality of the button, just display the text. So just use Label text control.
As shown below, in the control diagram on the left, find the Label control. The Label control is under "Display Widgets" (translated as display widgets). Select the Label control and drag it to the design form in the middle of ②. Then select the label object at ③, find the text file attribute in the attribute column of the label object at ④, and modify the text inside to "Hello World!". In this way we have displayed "Hello World" in the window. Of course, double-clicking the Label control in the middle can also modify its text properties. For beginners, it is better to modify it step by step, so as to learn how to use the "Ui Designer". Here we have completed the design of displaying "Hello World!"
Insert image description here

Project compilation & debugging & running

After completing the above "Hello World!", we are definitely going to compile and run our program and see how it works!
Follow the steps below, first return to the editing page, and then click the green triangle symbol in the lower left corner of ② (or press the Ctrl + R shortcut key to compile and run). Compilation information will be output during editing. Click ③ in the compilation output window to see When you go to the compilation information during compilation, you can see compilation warnings, compilation errors, compilation links, related compiler compilation processes, etc.
Insert image description here
The newly installed Qt Creator under Ubuntu, no surprise, will report a "Cannot find -lgL" error when compiling for the first time.
Since the Qt5.0 library is linked to OpenGL by default, but OpenGL is not installed on the Ubuntu machine, we need to install the OpenGL Library under Ubuntu. Enter the following command in the Ubuntu terminal.

sudo apt-get install libglu1-mesa-dev

After the installation is complete, let's click on the green triangle in the lower left corner to try again, and you can see the following results! You can see that there is no error message at ② in the picture below. If there are other errors reported, it is recommended to go back to Chapter 1 C++ Environment Settings to find the relevant instructions for C++ environment configuration and install the corresponding libraries. Maybe beginners skip C++ and go directly to Qt. Qt also depends on the C++ environment!
The running result is as shown in ③. A window pops up, and in the middle is the Hello World we designed!
Insert image description here
If you need to debug, please close the "Hello World!" window above first, and click the "x" in the upper right corner to close it! Click as follows, right-click in the program to set a breakpoint, and then click the Debug green triangle button at ③ in the lower left corner. However, we rarely use debugging. This simple program can completely predict its running process. If we want to know its running process, we can use this debugging function to understand the running process of the Qt program!
Insert image description here

Developed using Qt Designer

This chapter will introduce the use of Qt Designer that comes with Qt Creator. It is more convenient to use Qt Designer to construct UI interface. It is characterized by convenient layout and relatively vivid appearance.

Develop programs using UI designer

In this section we continue to learn how to use Qt Designer to develop programs. Qt Designer is just a function of Qt Creator. Don't get confused. Qt Designer is also called UI designer or UI designer, which all refer to the same thing. The following is a brief introduction to using the UI designer to develop a program, taking connecting signals and slots as an example to briefly introduce the development process. Finally, let's consider the benefits and inconveniences of this development approach.

Add a button to the UI file

Create a new project as 02_designer_example. If you don't know how to create a new project, please go back to Section 3.6. The steps are the same. The project creation process will not be described in detail here. The newly created project is as follows. In order to facilitate screenshots, the author has closed the project "01_hello_world" in Section 3.6. The rest is our new project 02_designer_example.
Insert image description here
The method of adding a button is the same as the method of adding a Label in Section 3.6.3. Find the Push Button on the left and drag it to the middle display form, as shown below.
Insert image description here
And change the text attribute (text attribute) of this PushButton to "Close Program". In Section 4.1.2, we will design that clicking this button will close this window and close this program.
Insert image description here

Connect signals and slots in UI files

There are two ways to connect signals and slots in the UI designer. Beginners may not understand what Qt's signals and slots are.
Here is a brief introduction to the functions of signals and slots. The so-called signal is the signal sent by an object, and the slot means that when the object sends the signal, the corresponding connected slot is executed or triggered. The above is an explanation of layman's terms. You can learn about Qt's signal and slot mechanism in the next chapter. Now we only need to have a basic understanding of this signal and slot. It can be said that signals and slots are essential in Qt. In order for events to take corresponding actions, signals and slots must be used.

The first method of connecting signals and slots in the UI designer:
In the upper part of the main form, we can see some small buttons, as shown in the frame part of the picture below. Use the mouse to hover over these buttons to see what the button does. The button for the signal slot connection is also above.
Insert image description here
Click the signal slot connection button as follows, as shown in ① in the figure below. Click to enter the signal slot connection mode (if you want to exit the signal slot connection mode, click the button on the left of ①). After entering the signal and slot connection mode, select us with the mouse. Click the "Close Program" button, press and hold the button, and then drag it outward with the mouse, as in ②. At this point, the signal slot connection symbol will appear.
Insert image description here
Then follow the steps in the figure below to select the signal of the "Close Program" pushButton button on the left. You can see that an object can have multiple signals. The slot function of QMainWindow on the right, if there are other objects, does not necessarily only have the slot function (slot) of MainWidnow on the right, it may also be the slot of other objects. We select the clicked() signal of the button and connect it to the close() slot of the MainWindow object. This completes the connection between the signal and the slot, which is very simple. We can also predict the function of this signal and slot. When the "Close Program" pushButton emits the clicked() signal (that is, the click signal).
This signal is emitted when the "Close Program" pushButton is clicked. It will trigger MainWindow's close(). This will cause the entire program to shut down. MainWindow's close() means to exit the closing program and exit the program.
Insert image description here
Complete the signal slot connection, as shown below. To return to the editing part mode, click the button marked in the figure below. The figure below shows the connection between signals and slots. We cannot see it in the editing component mode. Only the signal slot mode can see such an icon.
Insert image description here
Method 2 for connecting signals and slots in the UI designer:
Select the "Close Program" pushButton button, and then right-click it, as shown below. Select "Go to Slot".
Insert image description here
After clicking "Go to Slot", the following window pops up. This step is to first let us select the signal. Select as shown below. If you are careful, we will also find that this clicked() signal is not for pushButton, but for QAbstactButton. It's just that pusbButton inherits QAbstracButton, and also inherits this signal. In addition, we also see that other signals do not belong to pushButton and are also inherited. So the inheritance we learned in the basic part of C++.
The function in Qt is performed vividly! There is no need to override pushButton's clicked() event at all. pushButton only needs to inherit the clicked() event of the parent class!
Insert image description here
After clicking OK, it will jump to the slot function. This code is automatically generated by Qt Creator.
Insert image description here

At the same time, this slot function is declared in mainwindow.h.
Insert image description here
If we have learned C#, this is like the jump to event in C#. In fact, this convenient programming method is very similar to many programming IDEs. As long as we have a certain understanding of this IDE, it will not be difficult to learn.
Return to mainwindow.cpp and find the on_pushButton_clicked slot function. Write this->close() in this slot number; call the close() method to close the entire program.
Insert image description here

Compile and run the created UI project

Simply press Ctrl + r or click on the first green triangle symbol in the lower left corner to compile and run the project. The results of the operation are as follows. Click the "Close Program" button to see if the entire program is closed and exited? If careful students can still think about it, we have used two methods to connect signals and slots above. So how are they connected? Will it matter if they are both connected at the same time? Where is it connected? These are the questions we need to explore? Could it be that if the slot function is written in the second method, it will be automatically triggered? In the next section, we will continue to learn Qt signals and slots. If you understand how to write signals and slots, you can solve this mystery!

Insert image description here

Qt signals and slots

In this chapter, we learn Qt's signals and slots. Here is a chapter to learn Qt's signals and slots. This shows how important these signals and slots are. In the process of learning Qt, signals and slots are an indispensable part, and they are also the basis of Qt programming. They are a major innovation of Qt programming (in fact, they are very similar to C# events, and programming is similar). Qt signals and Slots have appeared in Qt4 or earlier, regardless of which version they belong to. There are just some differences in the way of writing signal and slot connections between Qt4 and Qt5. This tutorial does not explain how to write signals and slots in Qt4.
At the same time, starting from this chapter, we will not use Qt Designer for development, and we can also uncheck the *ui file when creating a new project. Why not develop programs using Qt Designer? The Qt Designer method is simple to develop programs, and its advantage is that it is convenient and fast. The advantage of the ui file is that it can see the overall layout more intuitively and quickly.
But the shortcomings are also obvious! One or two simple components are still possible, but too many controls are difficult to manage. You have to open the ui file every time to add new controls, which is difficult to manage with code! Readers have no way of knowing how the author layouts the interface, and the signal slot connection method can only be seen in the setupUi function after generating the code, or you need to enter the signal slot mode in the Ui designer to see the signal slot connection. , so very inconvenient! Less intuitive than code! Therefore, using code to draw the interface uniformly can exercise our layout ability and code logic ability!

Qt signals and slots mechanism

Signal & Slot are the basis of Qt programming and a major innovation of Qt. Because of the programming mechanism of signals and slots, it becomes more intuitive and simple to handle the interaction of various components of the interface in Qt.
Signal is an event that is emitted under specific circumstances, such as PushButton. The most common signal is the clicked() signal emitted when the mouse clicks. The most common signal of a ComboBox is CurrentIndexChanged() emitted when the selected list item changes. Signal.
The main content of GUI programming is the response to the signals of each component on the interface. You only need to know which signals are emitted under what circumstances, and respond and process these signals reasonably.
Slot is a function of response to a signal. A slot is a function, which is the same as a general C++ function. It can be defined in any part of the class (public, private or protected), can have any parameters, and can also be called directly.
The difference between slot functions and general functions is that the slot function can be associated with a signal. When the signal is emitted, the associated slot function is automatically executed.
The association between signals and slots is implemented using the QObject::connect() function, and its basic format is:

QObject::connect(sender, SIGNAL(signal()), receiver, SLOT(slot()));

connect() is a static function of the QObject class, and QObject is the base class of all Qt classes. The previous qualifier can be ignored when actually called, so it can be directly written as:

connect(sender, SIGNAL(signal()), receiver, SLOT(slot()));

Among them, sender is the name of the object that emits the signal, and signal() is the signal name. A signal can be regarded as a special function, which needs parentheses. If there are parameters, the parameters need to be specified. receiver is the name of the object that receives the signal, slot() is the name of the slot function, which needs to be enclosed in parentheses, and if there are parameters, the parameters need to be specified.
SIGNAL and SLOT are Qt macros used to specify signals and slots and convert their parameters into corresponding strings. For example, in the ui_mainwindow.h file of project 02_designer_example in Section 4.1 (the ui_mainwindow.h file is generated after compilation and is located in the build-02_designer_example-Desktop_Qt_5_12_9_GCC_64bit-Debug folder), there is the following statement in the setupUi() function:

QObject::connect(pushButton, SIGNAL(clicked()), MainWindow, SLOT(close()));

Its function is to associate the clicked() signal of the pushButton button with the slot function close() of the form (MainWindow), so that when the pushButton button (that is, the "X" button on the interface) is clicked, MainWindow's close() slot function. Here we can solve some of the questions in Section 4.1.3. We used the first method and did not see how the signals and slots are connected. In fact, it is in the generated code ui_mainwindow.h after the UI file is compiled!
Regarding the use of signals and slots, there are some rules to note:
A signal can be connected to multiple slots, for example:

connect(pushButton, SIGNAL(clicked()), this, SLOT(hide());
connect(pushButton, SIGNAL(clicked()), this, SLOT(close());

This is when an object pushButton is clicked, the form has two slots to respond, one hide() is used to hide the main form, and one close is used to close the main form. Here is just an example. In fact, after close() is executed, the hide() slot has no meaning because the program has already exited, but it is actually executed because it is connected in front of close(). When a signal is associated with multiple slot functions, the slot functions are executed sequentially in the order in which the connection is established.

When the signal and slot functions have parameters, the type of the parameter must be stated in the connect() function, but the parameter name does not need to be written.
Multiple signals can be connected to the same slot. For example, in 02_designer_example, we drag 2 pushButtons into the designed form. At the same time, let it connect the signals and slots according to the first method in the project in Section 4.1, and connect the clicked() signals of the three buttons to the close() slot function. After compilation, you can find the following signal slot connection statement in the setupUi() function in the ui_mainwindow.h file.

connect(pushButton,SIGNAL(clicked()),this,SLOT(close()));
connect(pushButton_2,SIGNAL(clicked()),this,SLOT(close()));
connect(pushButton_3,SIGNAL(clicked()),this,SLOT(close()));

In this way, when any pushButton is clicked, the close() function will be executed to close or exit the program. One signal can be connected to another signal (it shows that everything can be connected, very easy to use!), for example:

connect(pushButton, SIGNAL(objectNameChanged(QString)),this, SIGNAL(windowTitelChan
ged(QString)));

In this way, when one signal is transmitted, another signal is also transmitted to realize some special functions. Strictly speaking, the number and type of parameters of the signal and the slot need to be consistent, at least the parameters of the signal cannot be less than the parameters of the slot. If they do not match, a compilation error or a runtime error will occur. In classes that use signals and slots, the macro Q_OBJECT must be added to the class definition (especially important).
When a signal is emitted, its associated slot function is usually executed immediately, just like a normal call to a function.
Only after all slot functions associated with the signal have been executed, the code behind the signal is executed.
To summarize, as shown in the figure below, you can see that the sender and the sent signal are together, and the receiver and the received signal/slot are together. They cannot be written out of order in the connect() method! The sender sends a signal to the receiver using signals/slots.
Insert image description here

The method of connecting signal slots has been explained. Here is just a brief mention of the disconnection method. Beginners basically do not need to disconnect. Use disconnect(). disconnect(), this method overloads several functions, and the unblocking format is as follows
.

bool QObject::disconnect(const QObject *sender, const char *signal, const QObject *receiver, const
char *method)

Disconnect all signals or slots connected to myObject.

disconnect(myObject, 0, 0, 0);

Equivalent to non-static overloaded functions:

myObject->disconnect();

Disconnect everything connected to a specific signal.

disconnect(myObject, SIGNAL(mySignal()), 0, 0);

Equivalent to non-static overloaded functions:

myObject->disconnect(SIGNAL(mySignal()));

Disconnect from the designated recipient.

disconnect(myObject, 0, myReceiver, 0);

Equivalent to non-static overloaded functions:

myObject->disconnect(myReceiver);

The signal and slot mechanism is the basis of Qt GUI programming. Using the signal and slot mechanism can make it easier to associate signals with response codes.

How to create signals in the project

Let’s first create a new project and name the project 03_signal_slot_example. If you don’t know how to create a new project yet, please go back to Section 3.6 to see how the project is created. Just name the new project 03_signal_slot_example, and uncheck the *ui file (why cancel? You can find the reason at the beginning of Chapter 5). The other steps remain unchanged.
Since signals only need to be declared, no definition is required. So we only need to declare the signal in mainwindow.h. The code is as follows. The code in bold black in the figure below is the created signal. Create a void pushButtonTextChanged(); signal here. It is best to define the signal to fit the meaning of the signal itself. The author defines this signal as the signal after the button text changes.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 /* 引入QPushButton */
6 # include < QPushButton >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 signals:
	17      /* 声明一个信号,只需声明,无需定义*/
	18 void pushButtonTextChanged();


	19
	20
};
21 # endif      /* MAINWINDOW_H */

Lines 16 to 18 declare a signal void pushButtonTextChanged();. You can see that the signal does not need to be modified by keywords such as public.

How to create a slot in a project

The method of creating a slot is also very simple. It is also to directly declare the slot in mianwindow.h, and implement the definition of the slot in mianwindow.cpp. When declaring a slot, you must write the definition of the slot (the definition refers to the implementation of the function body), otherwise the compiler will An error will be reported.
The slot has the following characteristics:

  1. Slots can be any member functions, ordinary global functions, or static functions
  2. The parameters and return values ​​of the slot function and the signal must be consistent. According to the above slot characteristics, since we declared the signal void pushButtonTextChanged(); in Section 5.2, the slot function we declare
    must be of the return value type void and requires no parameters. So the code to declare the slot is as follows. In addition, we also declare a QPushButton object pushButton. The object pushButton can be written as abbreviation btn. This depends on personal habits! The abbreviated name is recommended not to be incomprehensible! Also declare a slot for button clicks.
1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 /* 引入QPushButton */
6 # include < QPushButton >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16
	17 signals:
	18      /* 声明一个信号,只需声明,无需定义*/
	19 void pushButtonTextChanged();


	20
	21 public slots:
	22      /* 声明一个槽函数*/
	23 void changeButtonText();


	24
	25      /* 声明按钮点击的槽函数*/
	26 void pushButtonClicked();


	27
	28 private:
	28      /* 声明一个对象pushButton */
	30 QPushButton * pushButton;
	31
};
32 # endif      /* MAINWINDOW_H */

Line 23 declares a slot function void changeButtonText();.
Line 26 declares a slot function void pushButtonClicked();.
Line 31 declares a QPushButton object pushButton. Implement the declared slot functions void changeButtonText(); and void pushButtonClicked();
in mainwindow.cpp .
The pushButton object is also instantiated. code show as below.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置窗体的宽为800,高为480 */
	7 this->resize( 800, 480 );
	8
	9       /* 实例化pushButton对象*/
	10 pushButton = new QPushButton( this );
	11
	12      /* 调用setText()方法设定按钮的文本*/
	13 pushButton->setText( "我是一个按钮" );
	14
}


15
16 MainWindow::~MainWindow()
17
{
    
    
	18
	19
}


20
21              /* 实现按钮点击槽函数*/
22 void MainWindow::pushButtonClicked()
23
{
    
    
	24      /* 使用emit发送信号*/
	25 emit pushButtonTextChanged();
	26
}


27
28              /* 实现按钮文本改变的槽函数*/
29 void MainWindow::changeButtonText()
30
{
    
    
	31      /* 在槽函数里改变按钮的文本*/
	32 pushButton->setText( "被点击了!" );
	33
}



Line 7 sets the size of the program window. If not set, the window will be at the minimum resolution. Here, set the width to 800 and the height to 480. It happens to be one of the resolutions in the atomic RGB LCD screen. Actual development only needs to be developed at the actual resolution of the hardware. This tutorial is developed with 800*480 resolution. It is not recommended to develop with a resolution lower than this. The resolution is too low and too little content is displayed.
Line 10, instantiate the pushButton object in the heap, and specify the parent object as this. Because what we declared in mainwindow.h is a pointer type object. In fact, the prototype of QPushButton(this) is QPushButton(QWidget *parent = nullptr). We have already learned about overloading in Section 2.2.3 of C++ Basics. In fact, there are the following two initialization methods in the QPushButton class. This is also the embodiment of C++ overloading in Qt.

QPushButton(const QString &text, QWidget *parent = nullptr)
QPushButton(const QIcon &icon, const QString &text, QWidget *parent = nullptr)

In lines 22 and 29, the slot method is implemented.

How to connect signals and slots in a project

Sections 5.2 and 5.3 only declare signals and define slots, and you need to connect signals and slots in the project. The code to complete the connection is as follows.
The code for signal slot connection is as follows.

connect(pushButton, SIGNAL(clicked()), this, SLOT(pushButtonClicked()));
connect(this, SIGNAL(pushButtonTextChanged()), this, SLOT(changeButtonText()));

Note that the object that sends the signal, and the object that receives the signal. Because our pushButtonClicked() is a slot defined in this class, we use this to receive it. In the same way, pushButtonTextChanged() is also a signal defined by this class. So the sender writes this. changeButtonText() is also a slot function of this class, so the object receiving the slot is also this. Many beginners don't understand who should write the sender of the signal and the receiver of the slot. We need to carefully read the above code and the definition of the signal and slot mechanism in Section 5.1 to slowly understand it.
The code for signal slot connection in mainwindow.cpp is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置窗体的宽为800,高为480 */
7 this->resize(800,480);
8
9 /* 实例化pushButton对象*/
10 pushButton = new QPushButton(this);
11
12 /* 调用setText()方法设定按钮的文本*/
13 pushButton->setText("我是一个按钮");
14
15 /* 信号与槽连接*/
16 connect(pushButton, SIGNAL(clicked()), this,
SLOT(pushButtonClicked()));
17 connect(this, SIGNAL(pushButtonTextChanged()), this, SLOT(changeButtonText()));
18 }
19
20 MainWindow::~MainWindow()
21 {
    
    
22
23 }
24
25 /* 实现按钮点击槽函数*/
26 void MainWindow::pushButtonClicked()
27 {
    
    
28 /* 使用emit发送信号*/
29 emit pushButtonTextChanged();
30 }
31
32 /* 实现按钮文本改变的槽函数*/
33 void MainWindow::changeButtonText()
34 {
    
    
35 /* 在槽函数里改变按钮的文本*/
36 pushButton->setText("被点击了!");
37 }

Lines 16 and 17 connect the signal and the slot. The whole process is that when the button is clicked, pushButtonClicked() is triggered. The pushButtonTextChanged() signal is sent in the pushButtonClicked() slot. The changeButtonText() slot responds to the pushButtonTextChanged() signal. We changeButtonText The () slot implements
the corresponding action (event). The final effect is that the text of the button changes from "I am a button" to "It was clicked!" when it is clicked.
After compiling and running the program, the following is shown before clicking the button.
Insert image description here
After clicking the button.
Insert image description here
Although the above program is simple, we finally implemented custom signals and slots.

Learn to use signals and slots of Qt classes

There are a large number of signals and slots in Qt, all of which are customized by Qt. It is basically enough for us. If we do not find the signals and slots we want, we can define our own signals and slots according to the method of customizing signals and slots in sections 5.2~5.4. So how do we use Qt signals and slots?
To use Qt's signals and slots, we must know what signals and slots there are. In the code in Section 5.4.

connect(pushButton, SIGNAL(clicked()), this, SLOT(pushButtonClicked()));

As shown in the figure below, hold down the Ctrl key and click clicked() to enter the definition of the clicked() signal.
Insert image description here
Entering the definition of QPushButton, we see that QPushButton not only has clicked signals, but also other signals, and also has slot functions of QPushButton (return to the previous step and press Alt + left arrow key). Here we just briefly looked at how to find other signals and slots among known signals and slots. In fact, during development, we often need to use the Qt help documentation to view the signals and slots defined by Qt. We will explain the use of Qt help documents in the next chapter. The help documents include how to view Qt's signals and slots, etc.
Insert image description here

Qt Creator usage tips

In any programming IDE software, there are corresponding programming skills. In this chapter we focus on the two most commonly used techniques - the use of Qt Creator's shortcut keys and the use of Qt's help documentation. The most important one is in Qt's help documentation. It can be said that the Qt help document is actually a tutorial. Any other Qt tutorials are not as detailed as the Qt document and are only in English. This is still a bit difficult for us beginners to get started. Below, the author and everyone will learn how to use Qt Creator's shortcut keys and Qt's help documentation.
6.1 Qt Creator shortcut keys
6.2 Use of Qt help documents

Qt Creator shortcut keys

In Qt Creator, if you don't know the shortcut keys for certain function buttons, you can move the mouse over the button to know its shortcut keys. As shown in the picture below, if you want to know what the shortcut key for running is, then we move the mouse to the run button in the lower left corner of QtCreator. At this time, it will prompt that the shortcut key for running is "Ctrl + R". Of course, it requires the English input method to take effect.
Insert image description here
There are many shortcut keys in Qt, and it is impossible for us to remember so many shortcut keys. We just need to use commonly used shortcut keys.
We won't talk about simple Ctrl + C and Ctrl + V copy and paste, etc. These are the same operations under Windows.
Commonly used shortcut keys are listed in the following table.
Insert image description here
Insert image description here
The above shortcut keys may conflict with the shortcut keys of Ubuntu or Windows systems, or some functions do not have shortcut keys defined. We can also customize shortcut keys or modify the original shortcut keys in Qt Creator. The steps are as follows.
Insert image description here
Find the keyboard under the "Environment" item, as shown in the figure at ⑤, switch the shortcut key for bookmarks, "Ctrl + M" displays red, indicating that it
conflicts with the system shortcut key. We can select this item and press "Record" at ⑥ to re-record the shortcut keys for switching bookmarks.
Then click "Apply" and "OK". Some commands have not defined shortcut keys. If we want to use shortcut keys for this command, we can also follow the steps below to record and customize our shortcut keys. Be careful not to duplicate the system shortcut keys.
Insert image description here

The above Qt Creator shortcut keys are for reference only. In fact, there are not many commonly used keys in programming, just use the commonly used ones!

Use of Qt help documentation

In any IDE programming software, reference help documentation is indispensable. Some IDE programming software requires manual downloading of these help documents. Qt Creator does not need it. When we installed Qt, the help documentation has been installed in our "Installation Directory/Qt5.12.9/Docs/", using html text. We can use the browser to open this html text .
The help document in the installation directory under Ubuntu is as follows. The following figure is the help document under QtCore (the core module of Qt).
Insert image description here
We can also search for corresponding keywords directly under Qt Creator. As shown in the figure below, for example, if we want to view the QPushButton class, first click the help at ① and then click the drop-down at ② to select the index. Enter "QPushButton" at ③. You can also just enter "QPush" to match the index value. Click on the matching option, as shown in ⑤ in the figure below, which is the help document we explored.
Insert image description here
How to use the searched help documents? For example, if you want to see what properties and functions are available in the QPushButton class, you can view the properties and functions under the headings "Properties" and "Public Functions", as shown below. You can see that the QPushButton class has the following properties and functions that can be used.
Insert image description here
For another example, if we don't know what slots are available in this QPushButton class, we can continue to look down and find Public Slots! When we view the usage of a method, just click to view the usage of a method! Don’t forget to use the shortcut keys from the previous section (Alt + ← (left arrow key)) to return to the previous level, or enter the next level (Alt + → (right arrow key)).
Insert image description here
The process of using Qt's help documentation is basically the same as above. Beginners may find it difficult to read these English documents. They may ask, are there any Chinese help documents? We need to know that this is foreign software, because the help documentation may be updated and changed, and translation requires manpower and time. Moreover, the original meaning of the translation may not be close to the original Qt help documentation. Let’s just read Qt’s most authoritative and comprehensive help document! If you want to learn Qt well, the help documentation is indispensable! In fact, Qt
's help document is a very large and very good tutorial. Our tutorial is just to guide you to get started with Qt, and to guide you to learn commonly used controls and methods in Qt, a very large document. Qt comes with a lot of examples for reference, which Qt does very well. We still need to practice more when reading the help documentation. It’s not just that we can master it by reading the help documentation. Only by practicing will we know that the basics depend on practice.

Guess you like

Origin blog.csdn.net/zhuguanlin121/article/details/132259768