C++ QT(2)

Qt control

Lao Tzu once said: "The difficult things in the world must be done with ease; the great things in the world must be done with details." No matter how complex the project is, it is composed of small parts. As long as you master the basics of Qt, you don't have to worry about big projects! From this chapter, we start to learn Qt widgets, and each type of widgets will choose one as an example to explain their usage. Through examples, you can draw inferences about other cases from one instance. This chapter is also pure code programming and does not use the Qt Designer graphical interface to develop programs. The author thinks that the code of pure code programming is easy for people to understand, and the design in Qt Designer does not seem to have too much logic at all. In this chapter, we can learn common control initialization methods, set the size and position of the form, color, text, and design creative examples to quickly learn how to use various controls, and strive to write examples practically, with detailed code comments. Because there are so many controls, if you feel that learning controls is boring, you can refer to this control (component) when you use it. It is not necessary to master all of them at once. The purpose of this chapter is to understand the types of Qt controls and how to use them.
The noteworthy section is section 7.1.3, which explains how to add resource images and qss files. For the following routines, you can refer to Section 7.1.3 to add resource images, and do not repeat this adding step.

Sections 7.8 and 7.9 are often used to process data and build models in embedded systems. You should spend more time studying these two sections.

button

In Qt, the most commonly used control is the button. With the button, we can click it to respond to events and achieve the effect of human-computer interaction. Whether it is embedded or PC, buttons are indispensable for interface interaction.
Qt button component is one of the commonly used components. Qt has six built-in button components as follows:
Insert image description here
(1) QPushButton: push button
(2) QToolButton: tool button
(3) QRadioButton: selection button
(4) QCheckBox: check box
(5) QCommandLinkButton: Command link button
(6) QDialogButtonBox: Dialog button
The functions of these six button components are briefly described as follows:
QPushButton inherits the QAbstractButton class and is inherited by QCommandLinkButton. Typically used to execute commands or trigger events.
QToolButton inherits the QAbstractButton class. A button for quick access to a command or option, usually in a ToolBar. Tool buttons usually display icons instead of text labels. ToolButton supports auto-floating. In auto-lift mode, the button only draws its three-dimensional frame when the mouse is pointed at it.
QRadioButton inherits the QAbstractButton class. RadioButton Radio buttons (radio boxes) usually appear in groups and are used to provide two or more mutually exclusive options.
QCheckBox inherits QAbstractButton. The difference between a check button (check box) and a RadioButton is the selection mode. The radio button provides multiple selections, and the check button provides multiple selections.
The Chinese name of the QCommandLinkButton control is "command link button". QCommandLinkButton inherits QPushButton. The QCommandLinkButton control is similar to the RadioButton in that it is used to select an item among mutually exclusive options. On the surface, it looks the same as a flat button, but in addition to the normal text description text on the button, the CommandLinkButton will also carry an arrow icon by default, indicating that pressing the button will open another window or page.
QDialogButtonBox button box (button box) is packaged by the QDialogButtonBox class.
QDialogButtonBox inherits QWidget. Commonly used to customize buttons in dialog boxes, such as "OK" and "Cancel" buttons.
The available properties, signals and slots of the six buttons mentioned above can be viewed in the Qt help document when needed. Here we skip introducing their available attributes and signals and slots. Below we use examples to explain how each button is used, and explore together what effects they can achieve.

QPushButton

Introduction to controls

We have already come into contact with QPushButton in Chapter 4. We connected signals and slots in Qt Designer to realize the function of closing the program. Let's start again by writing a program to implement a small example using QPushButton to connect signals and slots.

usage example

Example 04_qpushbutton Window skinning (difficulty: easy), change the color of the window by clicking different buttons.
Create a new project named 04_qpushbutton. Do not check "Generate form" in the new routine. It can inherit the QMainWindow class by default. If you don't know how to create a new project yet, it is recommended to go back to Section 3.6 to see how to create a new project.
Complete as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

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 private:
	17      /* 声明一个QPushButton对象pushButton1 */
	18 QPushButton * pushButton1;
	19      /* 声明一个QPushButton对象pushButton2 */
	20 QPushButton * pushButton2;
	21
	22 private slots:
	23      /* 声明对象pushButton1的槽函数*/
	24 void pushButton1_Clicked();


	25      /* 声明对象pushButton2的槽函数*/
	26 void pushButton2_Clicked();


	27
};
28 # endif      /* MAINWINDOW_H */

Line 6 introduces the QPushButton class.
Lines 18 and 20 declare two QPushButton objects.
Lines 24 and 26 declare the slot functions of two QPushButton objects.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置宽高为800×480,位置在0, 0。(0, 0)代表原点,Qt默认最左上角的点为原
点*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化两个按钮对象,并设置其显示文本为窗口皮肤1和窗口皮肤2 */
10 pushButton1 = new QPushButton("窗口皮肤1", this);
11 pushButton2 = new QPushButton("窗口皮肤2", this);
12
13 /* 设定两个QPushButton对象的位置*/
14 pushButton1->setGeometry(300,200,80,40);
15 pushButton2->setGeometry(400,200,80,40);
16
17 /* 信号槽连接*/
18 connect(pushButton1, SIGNAL(clicked()), this,
SLOT(pushButton1_Clicked()));
19 connect(pushButton2, SIGNAL(clicked()), this,
SLOT(pushButton2_Clicked()));
20 }
21
22 MainWindow::~MainWindow()
23 {
    
    
24 }
25
26 /* 槽函数的实现*/
27 void MainWindow::pushButton1_Clicked()
28 {
    
    
29 /* 设置主窗口的样式1 */
30 this->setStyleSheet("QMainWindow {
    
     background-color: rgba(255, 245,
238, 100%); }");
31 }
32
33 /* 槽函数的实现*/
34 void MainWindow::pushButton2_Clicked()
35 {
    
    
36 /* 设置主窗口的样式2 */
37 this->setStyleSheet("QMainWindow {
    
     background-color: rgba(238, 122,
233, 100%); }");
38 }

Line 7 sets the display position and display size of the program window. If not set, the running program window may appear in a certain position in Ubuntu, but in Windows it usually appears in the middle.
Lines 10 and 11 actualize the QPushButton object. During initialization, you can pass in a QString type string as the button's display text.
Line 14 sets the size and position of the button. The size of the button cannot be set too small, otherwise the text on the button may not be fully displayed.
Lines 18 and 19 connect the signals and slots of the two QPushButton objects.
Lines 27 to 38 implement two QPushButton slot functions, set the style sheet of the main form, and set the rgba parameter of background-color to change the background color of the form. Regarding what a style sheet is and how to set it up, a section will be dedicated to explaining it later.
The specific code in the source file "main.cpp" is as follows, which is generated when creating a new project and has no changes.

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
}



running result

After the program is compiled and run, click the Window Skin 1 button, and the main form will display as follows.
Insert image description here

Click the Window Skin 2 button, and the main form will appear as follows.
Insert image description here

QToolButton

Introduction to controls

The difference between a tool button (QToolButton) and an ordinary button (QPushButton) is that a tool button (QToolButton) can have an icon. The difference here is that the background images of icons and buttons are different. Usually we set different buttons on toolbars (toolbars) like QToolBar. If these buttons also have icons and text, then QToolButton is a good choice.

usage example

Example 05_qtoolbutton Customize the toolbar (difficulty: easy).
Create a new project named 05_qtoolbutton. Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5       /* 引入QToolButton类*/
6 # include < QToolButton >
7       /* 引入QToolBar类*/
8 # include < QToolBar >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19      /* 声明一个QToolButton对象*/
	20 QToolButton * toolButton;
	21      /* 声明一个QToolBar对象*/
	22 QToolBar * toolBar;
	23
};
24 # endif      /* MAINWINDOW_H */

Lines 20 and 22 declare the QToolButton object and QtoolBar object.
The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QApplication >
3 # include < QStyle >
4
5 MainWindow::MainWindow( QWidget *parent )
6 : QMainWindow( parent )
	7
{
    
    
	8       /* 设置主窗体的位置和大小*/
	9 this->setGeometry( 0, 0, 800, 480 );
	10
	11      /* 实例化QToolBar对象*/
	12 toolBar = new QToolBar( this );
	13      /* 设置toolBar的位置和大小*/
	14 toolBar->setGeometry( 0, 0, 800, 100 );
	15
	16      /* 实例化QStyle类对象,用于设置风格,调用系统类自带的图标*/
	17 QStyle * style = QApplication::style();
	18
	19      /* 使用Qt自带的标准图标,可以在帮助文档里搜索QStyle::StandardPixmap */
	20 QIcon icon =
		style->standardIcon( QStyle::SP_TitleBarContextHelpButton );
	21
	22      /* 实例化QToolButton对象*/
	23 toolButton = new QToolButton();
	24
	25      /* 设置图标*/
	26 toolButton->setIcon( icon );
	27      /* 设置要显示的文本*/
	28 toolButton->setText( "帮助" );
	29      /* 调用setToolButtonStyle()方法,设置toolButoon的样式,设置为文本置于
	         * 图标下方*/
	30 toolButton->setToolButtonStyle( Qt::ToolButtonTextUnderIcon );
	31
	32      /* 最后将toolButton添加到ToolBar里*/
	33 toolBar->addWidget( toolButton );
	34
}


35
36 MainWindow::~MainWindow()
37
{
    
    
	38
}



The process of this code is to initialize the toolBar (toolbar/toolbar) object, then initialize the toolButton (tool button) object, and set the style of the tool button. Finally, add the toolButton to the toolBar. This completes the design of the custom toolbar.
The specific code in the source file "main.cpp" is as follows, which is generated when creating a new project and has no changes.

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
}



running result

The final program results are as follows. Successfully embed custom tool buttons into the toolbar. This design can be seen in many software containing toolbars, and Qt can be used to achieve similar functions.
Insert image description here

QRadioButton

Introduction to controls

The QRadioButton widget provides a radio button (radio button) with a text label.
QRadioButton is an option button that can switch between checked or unchecked state.
Radio button boxes usually present the user with a "choose one from many" choice. That is, in a group of radio button boxes, only one radio button box can be selected at a time. By default, they are under the same parent object, and clicking them after initialization is mutually exclusive.

usage example

Example 06_radiobutton imitates the switch effect of a mobile phone (difficulty: medium). This example will realize the mobile phone switch effect, need to use the Qt style sheet, load the qss style sheet file, similar to Section 7.1.1, but write the style sheet into the qss file. Here we are slowly coming into contact with Qt's style sheets. It is precisely because of style sheets that we can write some more practical examples and more dazzling examples.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here

To add resource files, follow the steps below. Right click on the project and select Add New….
Insert image description here
Select a template, select Qt Template, select Qt Resource Files, and click Choose. We won’t go into details about Qt templates here. We will learn more about what templates we need to use in the future. Now there is no need to explain the usage of each template at once. In fact, we don’t use many commonly used ones.
Insert image description here
Fill in the name of the resource file (you can write any one, the author abbreviates it as res), and it will be added to the project path by default. The following steps can be done by default, click Finish.
Insert image description here
After the resource file is created, you will enter the res.qrc file editing mode by default (if it is closed, you can right-click the file and click "Open in Editor"), click Add Prefix to add a prefix. The purpose of adding a prefix is ​​to facilitate classification management of files. For example, we now add the prefix / at point ⑪. "/" must be written, otherwise the path will not be found, which is a bit like the root node of Linux.
Insert image description here
After adding the prefix, we add resource images, placed under the /images prefix. Here we have prepared two pictures, which are under the images folder of this project path (the images folder is manually created first). As shown in the figure below, after adding, you need to press "Ctrl + S" to save res.qrc to see the result on the left. The addition is completed as shown below.
Insert image description here
Add qss file. QSS files are style sheet files associated with Qt programs. It consists of the look and feel of GUI elements, including layout, color, mouse behavior, size, and fonts. It's a style that one can incorporate into a UI (User Interface). Similar to HTML's CSS, Qt's style sheets are plain text format definitions. These style definitions can be loaded and parsed when the application is running, so that the application's interface presents different effects.
Insert image description here
Create a new style.qss file, as shown below. It will be added to the project path by default. The following steps can be done by default.
Insert image description here
The qss file is added as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 #ifndef MAINWINDOW_H
2 #define MAINWINDOW_H
3
4 #include <QMainWindow>
5 /* 引入QRadioButton */
6 #include <QRadioButton>
7
8 class MainWindow : public QMainWindow
9 {
    
    
10 Q_OBJECT
11
12 public:
13 MainWindow(QWidget *parent = nullptr);
14 ~MainWindow();
15
16 private:
17 /* 声明两个QRadioButton对象*/
18 QRadioButton *radioButton1;
19 QRadioButton *radioButton2;
20 };
21 #endif // MAINWINDOW_H

Declare two QRadioButton objects on lines 18 and 19.
The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 主窗体设置位置和显示的大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8 this->setStyleSheet( "QMainWindow {
    
    background-color: rgba(200, 50,
100, 100%);}" );
	9
	10      /* 实例化对象*/
	11 radioButton1 = new QRadioButton( this );
	12 radioButton2 = new QRadioButton( this );
	13
	14      /* 设置两个QRadioButton的位置和显示大小*/
	15 radioButton1->setGeometry( 300, 200, 100, 50 );
	16 radioButton2->setGeometry( 400, 200, 100, 50 );
	17
	18      /* 设置两个QRadioButton的显示文本*/
	19 radioButton1->setText( "开关一" );
	20 radioButton2->setText( "开关二" );
	21
	22      /* 设置初始状态,radioButton1的Checked为false,另一个为true*/
	23 radioButton1->setChecked( false );
	24 radioButton2->setChecked( true );
	25
}


26
27 MainWindow::~MainWindow()
28
{
    
    
	29
}



Lines 23 and 24 set the initialization state of the QRadioButton object to make them mutually exclusive.
The specific code in the source file "main.cpp" is as follows. We need to load the qss file in main.cpp.

1 # include "mainwindow.h"
2
3 # include < QApplication >
4                       /* 引入QFile */
5 # include < QFile >
6
7 int main( int argc, char *argv[] )
8
{
    
    
	9 QApplication a( argc, argv );
	10              /* 指定文件*/
	11 QFile file( ":/style.qss" );
	12
	13              /* 判断文件是否存在*/
	14 if ( file.exists() )
	{
    
    
		15      /* 以只读的方式打开*/
		16 file.open( QFile::ReadOnly );
		17      /* 以字符串的方式保存读出的结果*/
		18 QString styleSheet = QLatin1String( file.readAll() );
		19      /* 设置全局样式*/
		20 qApp->setStyleSheet( styleSheet );
		21      /* 关闭文件*/
		22 file.close();
		23
	}
	24 MainWindow w;
	25 w.show();
	26 return(a.exec() );
	27
}



Lines 11 to 23 read the contents of style.qss. and set global styles.
The specific code in the source file "style.qss" is as follows, which is similar to the css syntax in HTML. If you don't know how to write qss content, you can refer to the Qt help document and search for "qt style" in it. Find relevant examples for reference. Here we only have a preliminary understanding of this qt style.

1 QRadioButton {
    
    
	2 spacing	: 2px;
	3 color		: white;
	4
}
5 QRadioButton::indicator {
    
    
	6 width		: 45px;
	7 height	: 30px;
	8
}
9 QRadioButton::indicator : unchecked {
    
    
	10 image : url( : / images / switch_off.png );
	11
}
12 QRadioButton::indicator : checked {
    
    
	13 image : url( : / images / switch_on.png );
	14
}

In lines 10 and 13, set the background image of the QRadioButton indicator. In this way, when they click to switch, they will see a switch-like effect.

running result

The effect of the compiled program is as follows. Click to close switch 1, switch 2 is on; click switch 2, switch 1 is on.
Because they have mutually exclusive effects by default. In some cases we need to use this effect. For example, when we watch videos online, we often need to switch lines. There may be several lines, but only one is active, so we can apply it in this direction.
Insert image description here

In this example, we learned how to add resources, and the steps are also detailed. You can refer to this routine to add resource files in the following routines, and we will not explain the adding process in detail. We have already had a preliminary understanding of Qt's style sheet files. If you want to make a good-looking interface, Qt's style sheet files are indispensable. Maybe we don't understand the syntax of Qt style sheets and don't know how to start. We can learn while learning, and we can refer to the usage in the Qt help document. The functions of qss are more than that. The focus now is to learn the QRadioButton control.

QCheckBox

Introduction to controls

QCheckBox inherits QAbstractButton. The difference between a check button (check box) and a RadioButton is the selection mode. The radio button provides multiple selections, and the check button provides multiple selections.

usage example

Example 07_qcheckbox, three-state selection box (difficulty: easy). Using a QCheckBox, the user can change the state of the check box by clicking on it.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below. The author has added the qss file and three resource pictures. If you do not know how to add qss files and resource images, please refer to Section 7.1.3.

Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 /* 引入QCheckBox */
6 # include < QCheckBox >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明一个QCheckBox对象*/
	18 QCheckBox * checkBox;
	19 private slots:
	20      /* 声明QCheckBox的槽函数,并带参数传递,用这个参数接收信号的参数*/
	21 void checkBoxStateChanged( int );


	22
	23
};
24 # endif      /* MAINWINDOW_H */

Two QCheckBox objects are declared on lines 18 and 19.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 主窗体设置位置和显示的大小及背景颜色*/
7 this->setGeometry(0, 0, 800, 480);
8 this->setStyleSheet("QMainWindow {
    
    background-color: rgba(100, 100,
100, 100%);}");
9
10 /* 实例化对象*/
11 checkBox = new QCheckBox(this);
12
13 /* 设置QCheckBox位置和显示大小*/
14 checkBox->setGeometry(350, 200, 250, 50);
15
16 /* 初始化三态复选框的状态为Checked */
17 checkBox->setCheckState(Qt::Checked);
18
19 /* 设置显示的文本*/
20 checkBox->setText("初始化为Checked状态");
21
22 /* 开启三态模式,必须开启,否则只有两种状态,即Checked和Unchecked */
23 checkBox->setTristate();
24
25 /* 连接checkBox的信号stateChanged(int),与我们定义的槽
checkBoxStateChanged(int)连接*/
26 connect(checkBox, SIGNAL(stateChanged(int)), this,
SLOT(checkBoxStateChanged(int)));
27 }
28
29 MainWindow::~MainWindow()
30 {
    
    
31 }
32
33 /* 槽函数的实现*/
34 void MainWindow::checkBoxStateChanged(int state)
35 {
    
    
36 /* 判断checkBox的state状态,设置checkBox的文本*/
37 switch (state) {
    
    
38 case Qt::Checked:
39 /* 选中状态*/
40 checkBox->setText("Checked状态");
41 break;
42 case Qt::Unchecked:
43 /* 未选中状态*/
44 checkBox->setText("Unchecked状态");
45 break;
46 case Qt::PartiallyChecked:
47 /* 半选状态*/
48 checkBox->setText("PartiallyChecked状态");
49 break;
50 default:
51 break;
52 }
53 }

In line 23, it should be noted that setting the QCheckBox object checkBox needs to be set to three-state mode.
The specific code in the source file "main.cpp" is as follows. We need to load the qss file in main.cpp.

1 # include "mainwindow.h"
2
3 # include < QApplication >
4                       /* 引入QFile */
5 # include < QFile >
6
7 int main( int argc, char *argv[] )
8
{
    
    
	9 QApplication a( argc, argv );
	10              /* 指定文件*/
	11 QFile file( ":/style.qss" );
	12
	13              /* 判断文件是否存在*/
	14 if ( file.exists() )
	{
    
    
		15      /* 以只读的方式打开*/
		16 file.open( QFile::ReadOnly );
		17      /* 以字符串的方式保存读出的结果*/
		18 QString styleSheet = QLatin1String( file.readAll() );
		19      /* 设置全局样式*/
		20 qApp->setStyleSheet( styleSheet );
		21      /* 关闭文件*/
		22 file.close();
		23
	}
	24 MainWindow w;
	25 w.show();
	26 return(a.exec() );
	27
}



Lines 11 to 23 read the contents of style.qss. And set the global style.
The specific code in the source file "style.qss" is as follows.

1 QCheckBox{
    
    
2 spacing: 5px;
3 color: white;
4 }
5 QCheckBox::indicator {
    
    
6 width: 50px;
7 height: 50px;
8 }
9 QCheckBox::indicator:enabled:unchecked {
    
    
10 image: url(:/images/unchecked.png);
11 }
12 QCheckBox::indicator:enabled:checked {
    
    
13 image: url(:/images/checked.png);
14 }
15 QCheckBox::indicator:enabled:indeterminate {
    
    
16 image: url(:/images/indeterminate.png);
17 }

In lines 10 and 13, set the background image of the QCheckBox indicator. In this way, when they click to switch, they will see the three selection states of QCheckBox.

running result

The effect of compiling the program is as follows. Click the checkBox several times to see the three state switches of QCheckBox.
When the state is selected.
Insert image description here
half-selected state.
Insert image description here
Unchecked state.
Insert image description here
We often see this kind of three-state selection box when installing software. If the program we design has multiple options, we can also design this kind of selection box.

QCommandLinkButton

Introduction to controls

The Chinese name of the QCommandLinkButton control is "command link button". QCommandLinkButton inherits QPushButton. The CommandLinkButton control is similar to the RadioButton in that it is used to select an item among mutually exclusive options.
On the surface, it looks the same as a flat button, but in addition to the normal text description text on the button, the CommandLinkButton will also carry an arrow icon by default, indicating that pressing the button will open another window or page.

usage example

Example 08_qcommandlinkbutton link window (difficulty: easy). Using a QCommandLinkButton, click to open the system's window.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 /* 引入QCommandLinkButton */
6 # include < QCommandLinkButton >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明一个QCommandLinkButton对象*/
	18 QCommandLinkButton * commandLinkButton;
	19
	20 private slots:
	21      /* 声明槽函数,用于点击commandLinkButton后触发*/
	22 void commandLinkButtonClicked();


	23
	24
	25
};
26 # endif /* MAINWINDOW_H */

On line 18, a QCommandLinkButton object is declared.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 /* 引入桌面服务,用来打开系统文件夹对话框*/
3 #include <QDesktopServices>
4 /* 引入QUrl */
5 #include <QUrl>
6
7 MainWindow::MainWindow(QWidget *parent)
8 : QMainWindow(parent)
9 {
    
    
10 /* 主窗体设置位置和显示的大小*/
11 this->setGeometry(0, 0, 800, 480);
12
13 /* 实例化对象*/
14 commandLinkButton = new QCommandLinkButton(
15 "打开/home目录", "点击此将调用系统的窗口打开/home目录",this);
16
17 /* 设置QCommandLinkButton位置和显示大小*/
18 commandLinkButton->setGeometry(300, 200, 250, 60);
19
20 /* 信号槽连接*/
21 connect(commandLinkButton, SIGNAL(clicked()), this,
22 SLOT(commandLinkButtonClicked()));
23 }
24
25 MainWindow::~MainWindow()
26 {
    
    
27 }
28
29 void MainWindow::commandLinkButtonClicked()
30 {
    
    
31 /* 调用系统服务打开/home目录*/
32 QDesktopServices::openUrl(QUrl("file:home/") );
33 }

Line 14, when instantiated, the prototype is QCommandLinkButton::QCommandLinkButton(const QString &text, const QString &description, QWidget *parent = nullptr).
The specific code in the source file "main.cpp" is as follows. Generated when creating a new project, no changes.

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
}



running result

The results of compiling and running the program are as follows.
Click the Open /home directory button in the middle, and the result is as follows. The system pops up a window and opens it directly to the /home directory.
Insert image description here
After clicking to open the /home directory, the system will pop up the /home directory path window.
Insert image description here

QDialogButtonBox

Introduction to controls

Dialog boxes and message boxes typically present buttons in a layout that conforms to the platform's interface guidelines. Dialog boxes for different platforms always have different layouts. QDialogButtonBox allows developers to add buttons to it and will automatically use a layout appropriate for the user's desktop environment. In other words, we can use the system's own dialog button, or we can define our own dialog button.
The commonly used buttons in QDialogButtonBox are as follows. For more information, please refer to the Qt help documentation.
Insert image description here

usage example

Example 09_qdialogbuttonbox, customize the buttons in QDialogButtonBox (difficulty: easy). Use a QDialogButtonBox, and add buttons provided by Qt or custom buttons to the QDialogButtonBox.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5       /* 引入QDialogButtonBox */
6 # include < QDialogButtonBox >
7       /* 引入QPuhsButton */
8 # include < QPushButton >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19      /* 声明一个QDialogButtonBox对象*/
	20 QDialogButtonBox * dialogButtonBox;
	21
	22      /* 声明一个QPushButton对象*/
	23 QPushButton * pushButton;
	24
	25 private slots:
	26      /* 声明信号槽,带QAbstractButton *参数,用于判断点击了哪个按钮*/
	27 void dialogButtonBoxClicked( QAbstractButton * );


	28
	29
};
30 # endif      /* MAINWINDOW_H */

Line 18 declares a QDialogButtonBox object.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 /* 引入QDebug */
3 #include <QDebug>
4
5 MainWindow::MainWindow(QWidget *parent)
6 : QMainWindow(parent)
7 {
    
    
8 /* 主窗体设置位置和显示的大小*/
9 this->setGeometry(0, 0, 800, 480);
10
11 /* 实例化并设置按钮的盒子的大小和位置*/
12 dialogButtonBox = new QDialogButtonBox(this);
13 dialogButtonBox->setGeometry(300, 200, 200, 30);
14
15 /*使用Qt的Cancel按钮*/
16 dialogButtonBox->addButton(QDialogButtonBox::Cancel);
17
18 /*将英文"Cancel"按钮设置为中文"取消" */
19 dialogButtonBox->button(QDialogButtonBox::Cancel)->setText("取消
");
20
21 /* 设定位置与大小*/
22 pushButton = new QPushButton(tr("自定义"));
23
24 /* 将pushButton添加到dialogButtonBox,并设定ButtonRole为ActionRole
*/
25 dialogButtonBox->addButton(pushButton,
QDialogButtonBox::ActionRole);
26
27 /* 信号槽连接,带参数QAbstractButton *,用于判断用户点击哪个按键*/
28 connect(dialogButtonBox, SIGNAL(clicked(QAbstractButton * )),
29 this, SLOT(dialogButtonBoxClicked(QAbstractButton *)));
30 }
31
32 MainWindow::~MainWindow()
33 {
    
    
34 }
35
36 void MainWindow::dialogButtonBoxClicked(QAbstractButton *button)
37 {
    
    
38 /* 判断点击的对象是否为QDialogButtonBox::Cancel */
39 if(button == dialogButtonBox->button(QDialogButtonBox::Cancel)) {
    
    
40 /* 打印“单击了取消键” */
41 qDebug() <<"单击了取消键"<<endl;
42 /* 判断点击的对象是否为pushButton */
43 }else if(button == pushButton) {
    
    
44 /* 打印“单击了自定义键” */
45 qDebug() <<"单击了自定义键"<<endl;
46 }
47 }

Line 16, when instantiated, the prototype is void QDialogButtonBox::addButton(QAbstractButton *button,
QDialogButtonBox::ButtonRole role).
Lines 41 and 45, we use qDebug() for the first time. Qt generally uses qDebug() to print when debugging. This is basically the same function as cout in C++. It's just that Qt is customized as qDebug().
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of compiling and running the program are as follows. Click the custom button and cancel button, and you can see the corresponding click events in the application output window.
Insert image description here

Input widget

In the panel provided by the Qt Designer widget, 16 input components are provided as follows
Insert image description here
(1) Comb Box: combo box
(2) Font Comb Box: font combo box
(3) Line Edit: single-line edit box
(4) Text Edit: text Edit box
(5) Plain Text Edit: Plain text edit box
(6) Spin Box: Number rotation box
(7) Double Spin Box: Double precision number rotation box
(8) Time Edit: Time edit box
(9) Date Edit: Date Edit box
(10) Date/Time Edit: Date and time edit box
(11) Dial: Number dial box
(12) Horizontal Scroll Bar: Horizontal scroll bar (
13) Vertical Scroll Bar: Vertical scroll bar
(14) Horizontal Slider: Horizontal Slider
(15) Vertical Slider: Vertical Slider
(16) Key sequence Edit: Key sequence edit box
The functions of these sixteen button components are introduced as follows:
QComboBox inherits the QWidget class and is inherited by the QFontComboBox class. Typically used to display a list of options to the user, this method takes up the least amount of screen space.
QFontComboBox inherits QComboBox. The QFontComboBox widget is a combo box that allows the user to select a font family. The combo box is populated with an alphabetical list of font family names. FontComboBox is commonly used in toolbars, together with the ComboBox to control font size, and with the two ToolButtons for bold and italics.
QLineEdit inherits QWidget. The QLineEdit widget is a single-line text editor. Line editing allows users to enter and edit a line of plain text using a useful set of editing functions, including undo and redo, cut and paste, and drag and drop. By changing the line edit's echoMode(), it can also be used as a "write-only" field for input such as passwords.
QTextEdit inherits QAbstractScrollArea, which is inherited by QTextBrowser. QTextEdit is an advanced WYSIWYG viewer/editor that supports rich text formatting using html-style markup. It is optimized to handle large documents and respond quickly to user input. QTextEdit is used for paragraphs and characters. A paragraph is a formatted string that is word-wrapped to fit the width of the widget. When reading plain text, a newline represents a paragraph by default. A document consists of zero or more paragraphs. The text within a paragraph is aligned with the paragraph's alignment. Paragraphs are separated by hard line breaks. Each character in a paragraph has its own properties, such as font and color. QTextEdit can display images, lists and tables. If the text is too large to be viewed in the text editing view, scroll bars appear in the view.
QPlainTextEdit is an advanced viewer/editor with plain text support. It is optimized for handling large documents and responding quickly to user input.
QSpinBox inherits QAbstractSpinBox. is used to handle integers and discrete values ​​(for example: month names) while the QDoubl eSpinBox is used to handle floating point values. The difference between them is the type of data processed, and other functions are basically the same.
QSpinBox allows the user to select a value by clicking the up/down buttons or pressing the up/down buttons on the keyboard to increase/decrease the currently displayed value. Users can also enter values ​​manually.

QDoubleSpinBox inherits QAbstractSpinBox. QDoubleSpinBox is used to handle floating point values. QDoubleS pinBox allows the user to select the currently displayed value by clicking the Up and Down buttons or by pressing the Up or Down buttons on the keyboard. Users can also enter values ​​manually.
QTimeEdit inherits QDateTimeEdit. QTimeEdit is used to edit time, while QDateEdit is used to edit date.
QDateEdit inherits QDateTimeEdit. QDateEdit is used to edit dates, while QTimeEdit is used to edit time.
The QDateTimeEdit class provides a widget for editing dates and times. QDateTimeEdit allows the user to edit a date using the keyboard or arrow keys to increase or decrease the date and time values. The arrow keys can be used to move from one area to another in the QDateTimeEdit box.
The QDial class provides a circular range control (such as a speedometer or potentiometer). QDial is used when the user needs to control a value within a programmably defined range, and that range is either wraparound (for example, an angle measured from 0 to 359 degrees), or the dialog layout requires a square widget. Because QDial inherits from QAbstractSlider, the dial behaves like a slider. When wrapping() is false (the default), there is no real difference between sliders and dials. They share the same signals, slots and member functionality. Which one you use depends on your user expectations and application type.
QScrollBar inherits QAbstractSlider. The QScrollBar widget provides a vertical or horizontal scroll bar, allowing users to access portions of a document that are larger than the widget used to display the document. It provides a visual indication of the user's current position in the document and the number of visible documents. Scroll bars often come with additional controls that allow for more precise navigation.
QSlider inherits QAbstractSlider. The QSlider class provides a vertical or horizontal slider widget, a typical widget used to control bounded values. It allows the user to move a slider handle along a horizontal or vertical groove and converts the handle's position into an integer value within the legal range.
QKeySequenceEdit inherits QWidget. This widget allows the user to select a QKeySequence, which is often used as a shortcut. Recording starts when the widget receives focus and ends one second after the user releases the last key, often used as a record shortcut.

QComboBox

Introduction to controls

The QComboBox class provides components for a Qt drop-down combo box.

usage example

Example 10_qcombobox, select a province (difficulty: easy), select one of the items by clicking the drop-down button, and then print out the content of the currently selected item.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 /* 引入QComboBox */
6 # include < QComboBox >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明一个QComboBox对象*/
	18 QComboBox * comboBox;
	19
	20 private slots:
	21      /* 声明QComboBox对象的槽函数*/
	22 void comboBoxIndexChanged( int );


	23
	24
};
25 # endif      /* MAINWINDOW_H */

Line 20 declares a QComboBox object.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 /* 引入QDebug */
3 #include <QDebug>
4
5 MainWindow::MainWindow(QWidget *parent)
6 : QMainWindow(parent)
7 {
    
    
8 /* 设置主窗体的显示位置与大小*/
9 this->setGeometry(0, 0, 800, 480);
10
11 /* 实例化对象*/
12 comboBox = new QComboBox(this);
13
14 /* 设置comboBox的显示位置与大小*/
15 comboBox->setGeometry(300, 200, 150, 30);
16
17 /* 添加项,我们添加三个省份,作为comboBox的三个选项*/
18 comboBox->addItem("广东(默认)");
19 comboBox->addItem("湖南");
20 comboBox->addItem("四川");
21
22 /* 信号槽连接*/
23 connect(comboBox, SIGNAL(currentIndexChanged(int)), this,
24 SLOT(comboBoxIndexChanged(int)));
25 }
26
27 MainWindow::~MainWindow()
28 {
    
    
29 }
30
31 void MainWindow::comboBoxIndexChanged(int index)
32 {
    
    
33 /* 打印出选择的省份*/
34 qDebug()<<"您选择的省份是"<< comboBox->itemText(index)<<endl;
35 }

Lines 18 to 20 add Item, which is the item.
Lines 30 to 34, when the drop-down list is clicked to change the selected province, the currentIndexChanged(int) signal will be triggered, and the province name of the item will be printed accordingly.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of compiling and running the program are as follows. When you click the drop-down selection box to select a province, the slot function will print out the province you selected.
Insert image description here

Click to select "Hunan" and "The province you selected is Hunan" will be printed.
Insert image description here
QComboBox is often used in some items that require drop-down list selection. For example, if you have multiple account options for QQ login, you need this QComboBox.

QFontComboBox

Introduction to controls

The QFontComboBox class provides a combo box widget for drop-down selection of font families.

usage example

Example 11_qfontcombobox, font selection (difficulty: easy), select one of the items by clicking the drop-down button, and then print out the content of the currently selected item.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5       /* 引入QFontComboBox */
6 # include < QFontComboBox >
7       /* 引入QLable */
8 # include < QLabel >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19      /* 声明一个QFontComboBox对象*/
	20 QFontComboBox * fontComboBox;
	21      /* 声明一个Label对象,用于显示当前字体变化*/
	22 QLabel * label;
	23
	24 private slots:
	25      /* 声明QFontComboBox对象使用的槽函数*/
	26 void fontComboBoxFontChanged( QFont );
	27
	28
};
29 # endif      /* MAINWINDOW_H */

Line 20 declares a QFontComboBox object.
The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置主窗体的显示位置和大小*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化对象*/
10 fontComboBox = new QFontComboBox(this);
11 label = new QLabel(this);
12
13 /* 设置显示的位置与大小*/
14 fontComboBox->setGeometry(280, 200, 200, 30);
15 label->setGeometry(280, 250, 300, 50);
16
17 /* 信号与槽连接*/
18 connect(fontComboBox, SIGNAL(currentFontChanged(QFont)), this,
19 SLOT(fontComboBoxFontChanged(QFont)));
20 }
21
22 MainWindow::~MainWindow()
23 {
    
    
24 }
25
26 /* 槽函数实现*/
27 void MainWindow::fontComboBoxFontChanged(QFont font)
28 {
    
    
29 /* 将label里的文本内容设置为所选择的字体*/
30 label->setFont(font);
31
32 /* 定义一个字符串接收当前项的字体*/
33 QString str = "用此标签显示字体效果\n设置的字体为:" +
34 fontComboBox->itemText(fontComboBox->currentIndex());
35
36 /* 将字符串的内容作为label的显示内容*/
37 label->setText(str);
38 }

Lines 27 to 37, when the selected font changes, the slot function will set the font of the label and print the name of the current font.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of compiling and running the program are as follows. After clicking the FontCOmboBox font combo box to select a font, the font displayed on the Label label will change to the currently selected font. (Note that the fonts of Ubuntu and Windows are different, so the display effect may be different. The picture below shows the font display effect of Ubuntu.) Some software on mobile phones and computers have the function of
Insert image description here
setting fonts, which are selected by the user, so our QFontComboBox It can be applied to this situation. Of course, you can also set the font size, color, etc., which are designed by us freely.

QLineEdit

Introduction to controls

The QLineEdit widget is a single-line text editor. Line editing allows users to enter and edit a line of plain text using a set of useful editing functions. Includes undo and redo, cut and paste, and drag and drop. By changing the echoMode() of the line edit, it can also be used as a "write-only" field for input like passwords etc.

usage example

Example 12_qlineedit, a single-line input box (difficulty: easy), select one of the items by clicking the item of the drop-down button, and then print out the content of the currently selected item.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows. We gradually faded away comments such as introducing header files, setting the size and position of the main form and instantiating objects, and no longer wrote detailed comments. Readers are already very clear about this setting after reading the previous section.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QLineEdit >
6 # include < QPushButton >
7 # include < QLabel >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16 private:
	17      /* 声明一个QLineEdit对象*/
	18 QLineEdit * lineEdit;
	19
	20      /* 声明一个QPushButton对象*/
	21 QPushButton * pushButton;
	22
	23      /* 声明一个QLabel对象*/
	24 QLabel * label;
	25
	26 private slots:
	27      /* 声明一个槽函数,响应pushButton的clicked事件*/
	28 void pushButtonClicked();


	29
};
30 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 this->setGeometry(0, 0, 800, 480);
7
8 lineEdit = new QLineEdit(this);
9 lineEdit->setGeometry(280, 200, 200, 20);
10
11 pushButton = new QPushButton(this);
12 pushButton->setGeometry(500, 200, 50, 20);
13 pushButton->setText("确认");
14
15 label = new QLabel(this);
16 label->setGeometry(280, 250, 400, 20);
17 label->setText("您输入的内容是:");
18
19 /* 信号槽连接*/
20 connect(pushButton,SIGNAL(clicked()), this,
21 SLOT(pushButtonClicked()));
22 }
23
24 MainWindow::~MainWindow()
25 {
    
    
26 }
27
28 void MainWindow::pushButtonClicked()
29 {
    
    
30 /* 字符串变量str */
31 QString str;
32
33 str = "您输入的内容是:";
34 str += lineEdit->text();
35
36 /* 设置label里的文本显示内容*/
37 label->setText(str);
38 /* 在点击了确认键之后清空lineEdit单行输入框*/
39 lineEdit->clear();
40 }

Lines 28 to 40, after we complete the input in the radio input box, set the input content to the text content in the label.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of program compilation and running are as follows. After entering text content in the QLineEdit single-line input box and clicking the QPushButton confirmation button, the QLabel text content will display the content you entered. The QLineEdit will then clear and can be entered again.
Insert image description here
The simple use of QLineEdit is as above, and the author also briefly introduces its usage. To write a better example, we need to think proactively. For example, apply this QLineEdit to the password login window, enter the password, and then determine whether the password is the same as the default password before unlocking it.

QTextEdit

Introduction to controls

The QTextEdit class provides a viewer/editor widget.

usage example

Example 13_qtextedit text edit box (difficulty: easy), uses a QTextEdit to demonstrate text input, and uses two QPushButtons to simulate all selection and clearing of text editing. In QTextEdit, you can also use keyboard shortcuts (such as Ctrl+A) to complete operations such as selecting all, copying, and pasting. Qt provides functions such as select all, copy and paste, etc. to facilitate user operations. A simple example is used to demonstrate below.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3 # include < QTextEdit >
4 # include < QPushButton >
5
6 # include < QMainWindow >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明一个QTextEdit对象*/
	18 QTextEdit * textEdit;
	19
	20      /* 声明两个QPushButton对象*/
	21 QPushButton * pushButtonSelectAll;
	22 QPushButton * pushButtonClearAll;
	23
	24 private slots:
	25      /* 声明两个槽函数,响应按钮点击响应的事件*/
	26 void pushButtonSelectAllClicked();


	27 void pushButtonClearAllClicked();


	28
	29
};
30 # endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置主窗体显示的位置和大小*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例和对象,设置位置和显示大小*/
10 textEdit = new QTextEdit(this);
11 textEdit->setGeometry(0, 0, 800, 400);
12
13 /* 实例和对象,设置位置和显示大小,设置文本*/
14 pushButtonSelectAll = new QPushButton(this);
15 pushButtonSelectAll->setGeometry(200, 420, 50, 20);
16 pushButtonSelectAll->setText("全选");
17
18 /* 实例和对象,设置位置和显示大小,设置文本*/
19 pushButtonClearAll = new QPushButton(this);
20 pushButtonClearAll->setGeometry(500, 420, 50, 20);
21 pushButtonClearAll->setText("清除");
22
23 /* 信号槽连接*/
24 connect(pushButtonSelectAll, SIGNAL(clicked()), this,
25 SLOT(pushButtonSelectAllClicked()));
26 connect(pushButtonClearAll, SIGNAL(clicked()), this,
27 SLOT(pushButtonClearAllClicked()));
28
29 }
30
31 MainWindow::~MainWindow()
32 {
    
    
33 }
34
35 void MainWindow::pushButtonSelectAllClicked()
36 {
    
    
37 /* 设置焦点为textEdit */
38 textEdit->setFocus();
39 /* 判断文本编辑框内容是否为空,不为空则全选*/
40 if(!textEdit->toPlainText().isEmpty()){
    
    
41 /* 全选*/
42 textEdit->selectAll();
43 }
44 }
45
46 void MainWindow::pushButtonClearAllClicked()
47 {
    
    
48 /* 清空textEdit里的文本内容*/
49 textEdit->clear();
50 }
51

Lines 35 to 49, after we complete the input in the text input box and click the Select All button, we need to set the focus to textEdit, otherwise we will not be able to set Select All.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The result of compiling and running the program is as follows. After entering the text in the edit box, click the button to select all, and click Clear to clear all the contents in the edit box. The picture below shows the effect of clicking to select all.
Insert image description here

QPlainTextEdit

Introduction to controls

The QPlainTextEdit class provides a widget for editing and displaying plain text, often used to display multi-line text or simple text.

usage example

Example 14_qplaintextedit text browsing editor (difficulty: easy), use a QPlainTextEdit to read a file in the current project, and use a RadioButton to set the QPlainTextEdit to read-only.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QPlainTextEdit >
5 # include < QRadioButton >
6
7 # include < QMainWindow >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 声明对象*/
	19 QPlainTextEdit * plainTextEdit;
	20 QRadioButton * radioButton;
	21
	22 private slots:
	23      /* 槽函数*/
	24 void radioButtonClicked();


	25
	26
};
27 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 #include <QDir>
3 #include <QTextStream>
4 #include <QCoreApplication>
5
6 MainWindow::MainWindow(QWidget *parent)
7 : QMainWindow(parent)
8 {
    
    
9 /* 设置当前程序的工作目录为可执行程序的工作目录*/
10 QDir::setCurrent(QCoreApplication::applicationDirPath());
11
12 this->setGeometry(0, 0, 800, 480);
13
14 plainTextEdit = new QPlainTextEdit(this);
15 plainTextEdit->setGeometry(0, 50, 800, 430);
16
17 radioButton = new QRadioButton(this);
18 radioButton->setGeometry(650, 20, 100, 20);
19 radioButton->setText("只读模式");
20
21 /* 打开可执行程序目录里的moc_mainwindow.cpp,注意如果是Windows下
22 moc_mainwindow.cpp并不在当前目录,而在上一级目录"../moc_mainwindow.cpp
"*/
23 QFile file("moc_mainwindow.cpp");
24
25 /* 以只读模式打开,但是可以在plainTextEdit里编辑*/
26 file.open((QFile::ReadOnly | QFile::Text));
27
28 /* 加载到文件流*/
29 QTextStream in(&file);
30
31 /* 从文本流中读取全部*/
32 plainTextEdit->insertPlainText(in.readAll());
33
34 /* 信号槽连接*/
35 connect(radioButton, SIGNAL(clicked()), this,
36 SLOT(radioButtonClicked()));
37
38 }
39
40 MainWindow::~MainWindow()
41 {
    
    
42 }
43
44 void MainWindow::radioButtonClicked()
45 {
    
    
46 /* 检查radioButton是否选中*/
47 if(radioButton->isChecked()) {
    
    
48 /* 设置为只读模式*/
49 plainTextEdit->setReadOnly(true);
50 } else {
    
    
51 /* 设置为非只读模式*/
52 plainTextEdit->setReadOnly(false);
53 }
54 }

Lines 44 and 54, check if the radioButton is selected.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of compiling and running the program are as follows. When the program runs normally, it will open the "moc_mainwindow.cpp" file under the current path of the program (note that under Windows, moc_mainwindow.cpp should be written as ".../moc_mainwindow.cpp"), and in the QPlainTextEdit edit box It is editable,
when the read-only mode on the program interface is selected, the QPlainTextEdit edit box cannot be edited. On the contrary, you can cancel the read-only mode and edit again.
Insert image description here
With QTextEdit, why QPlainTextEdit? QPlainTextEdit can be understood as a low-profile version of QTextEdit. QPlainTextEdit supports plain text display, and QTextEdit supports rich text (supports multiple formats, such as inserting pictures, links, etc.) display. Just one more style. The display efficiency of QPlainTextEdit is higher than that of QTextEdit. If a large amount of text needs to be displayed, especially when the scroll bar is required to scroll back and forth, QPlainTextEdit is much better.

QSpinBox

Introduction to controls

The QSpinBox class provides a spinner widget.

usage example

Example 15_qspinbox window background opacity adjuster (difficulty: simple), use a QSpinBox to adjust the overall opacity of the program window.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSpinBox>
class MainWindow : public QMainWindow
{
    
    
	Q_OBJECT
public:
	MainWindow( QWidget *parent = nullptr );
	~MainWindow();
private:
/* 声明一个QSpinBox对象*/
	QSpinBox *spinBox;
private slots:
/* 槽函数*/
	void spinBoxValueChanged( int );
};
#endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 this->setGeometry(0, 0, 800, 480);
7
8 /* 设置主窗口背景颜色,rgb颜色标准,a代表不透明度(0~100)*/
9 this->setStyleSheet("QMainWindow{background-color: "
10 "rgba(100, 100, 100, 100%) }");
11
12 spinBox = new QSpinBox(this);
13 spinBox->setGeometry(350, 200, 150, 30);
14
15 /* 设置范围0~100 */
16 spinBox->setRange(0, 100);
17
18 /* 设置步长为10 */
19 spinBox->setSingleStep(10);
20
21 /* 设置初始值为100 */
22 spinBox->setValue(100);
23
24 /* 设置后缀*/
25 spinBox->setSuffix("%不透明度");
26
27 /* 信号槽连接*/
28 connect(spinBox,SIGNAL(valueChanged(int)), this,
29 SLOT(spinBoxValueChanged(int)));
30 }
31
32 MainWindow::~MainWindow()
33 {
    
    
34 }
35
36 void MainWindow::spinBoxValueChanged(int opacity)
37 {
    
    
38 /* 转换为double数据类型*/
39 double dobleopacity = (double)opacity / 100;
40
41 /* 设置窗体不透明度,范围是0.0~1.0。1则为不透明,0为全透明*/
42 this->setWindowOpacity(dobleopacity);
43 }

Line 42 sets the opacity of the main form.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The result of compiling and running the program is as follows. When the program is initialized, the interface is completely opaque, and the opacity value is 100%. When you click down to adjust the SpinBox, the opacity of the entire window will become smaller. When the opacity value becomes smaller, the window becomes transparent.
Insert image description here

QDoubleSpinBox

Introduction to controls

The QDoubleSpinBox class provides a spinner widget for handling floating point values. Basically the same function as QSpinBox, different from QSpinBox, the QDoubleSpinBox class deals with floating-point value data.

usage example

Example 16_qdoublespinbox window size adjuster (difficulty: easy), use a QDoubleSpinBox to adjust the overall size of the program window.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QDoubleSpinBox >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* 声明一个QDoubleSpinBox对象*/
	17 QDoubleSpinBox * doubleSpinBox;
	18
	19 private slots:
	20      /* 槽函数*/
	21 void doubleSpinBoxValueChanged( double );


	22
	23
};
24 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 this->setGeometry(0, 0, 800, 480);
7
8 /* 实例化和设置显示的位置与大小*/
9 doubleSpinBox = new QDoubleSpinBox(this);
10 doubleSpinBox->setGeometry((this->width() - 200) / 2,
11 (this->height() - 30) / 2,
12 200, 30);
13 /* 设置前缀*/
14 doubleSpinBox->setPrefix("窗口大小");
15
16 /* 设置后缀*/
17 doubleSpinBox->setSuffix("%");
18
19 /* 设置范围*/
20 doubleSpinBox->setRange(50.00, 100.00);
21
22 /* 设置初始值*/
23 doubleSpinBox->setValue(100.00);
24
25 /* 设置步长*/
26 doubleSpinBox->setSingleStep(0.1);
27
28 /* 信号槽连接*/
29 connect(doubleSpinBox, SIGNAL(valueChanged(double)),
30 SLOT(doubleSpinBoxValueChanged(double)));
31
32 }
33
34 MainWindow::~MainWindow()
35 {
    
    
36 }
37
38 void MainWindow::doubleSpinBoxValueChanged(double value)
39 {
    
    
40 /* 重新计算窗口的宽与高*/
41 int w = 800 * value / 100;
42 int h = 480 * value / 100;
43
44 /* 重新设置窗口的宽与高*/
45 this->setGeometry(0, 0, w, h);
46
47 /* 重新设置doubleSpinBox的显示位置*/
48 doubleSpinBox->setGeometry((this->width() - 200) / 2,
49 (this->height() - 30) / 2,
50 200, 30);
51
52 }

Lines 35 to 49 reset the width and height of the main form and the display position of doubleSpinBox.
The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



running result

The results of compiling and running the program are as follows. The window size of the program initialization interface is 100%. When clicking down to adjust the QDoubleSpinBox, the entire window will be reduced in proportion to the value in the QDoubleSpinBox, with a minimum of 50.00%. On the contrary, when clicking up to adjust the QDoubleSpinBox, The window size will be increased overall, up to 100.00%.
Insert image description here

QTimeEdit

7.2.8.1 Control Introduction
The QTimeEdit class provides a widget for editing time based on the QDateTimeEdit class. Examples are in Section 7.2.10.

QDateEdit

7.2.9.1 Control introduction
The QDateEdit class provides a widget for editing time based on the QDateTimeEdit class. An example is in section 7.2.10.
7.2.10 QDateTimeEdit
7.2.10.1 Introduction to the control
As you can see from the name, the QDateTimeEdit class provides a widget for editing date and time. QDateTimeEdit allows users to edit dates using the keyboard or arrow keys to increase or decrease date and time values. The arrow keys can be used to move from one area to another in the QDateTimeEdit box. It's actually a combination of QDateTimeEdit and QDateEdit.
7.2.10.2 Usage examples
Example 17_qdatetimeedit time and date display (easy difficulty), use a QDateTimeEdit, a QTimeEdit and a QDateEdit, pass in the current system time and date, and demonstrate the use of simple date and time controls.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QDateTimeEdit >
6 # include < QTimeEdit >
7 # include < QDateEdit >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 声明对象*/
	19 QDateTimeEdit * dateTimeEdit;
	20 QTimeEdit * timeEdit;
	21 QDateEdit * dateEdit;
	22
};
23 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9       /*实例化对象,传入当前日期与时间*/
	10 dateTimeEdit = new QDateTimeEdit(
		QDateTime::currentDateTime(), this );
	11 dateTimeEdit->setGeometry( 300, 200, 200, 30 );
	12      /* 弹出日期控件与否*/
	13      /* dateTimeEdit->setCalendarPopup(true); */
	14
	15      /* 实例化对象,传入当前时间*/
	16 timeEdit = new QTimeEdit( QTime::currentTime(), this );
	17 timeEdit->setGeometry( 300, 240, 200, 30 );
	18
	19      /* 实例化对象,传入当前日期*/
	20 dateEdit = new QDateEdit( QDate::currentDate(), this );
	21 dateEdit->setGeometry( 300, 280, 200, 30 );
	22
}


23
24 MainWindow::~MainWindow()
25
{
    
    
	26
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The result of compiling and running the program is as follows. When the program is initialized, the current time and date of the system are displayed respectively (note that the format displayed by the Qt program under Windows may be different. The following figure shows the date display format of the Qt program under Linux).
Insert image description here

QDial

7.2.11.1 Control Introduction
The QDial class provides a circular range control (such as a speedometer or potentiometer). QDial is used when the user needs to control a value within a programmably defined range, and that range is either wraparound (for example, an angle measured from 0 to 359 degrees), or the dialog layout requires a square widget. Because QDial inherits from QAbstractSlider, the dial behaves like a slider. When wrapping() is false (the default), there is no real difference between sliders and dials. They share the same signals, slots and member functionality. Which one you use depends on your user expectations and application type.
7.2.11.2 Usage Example
Example 18_qdial Speedometer (Difficulty: Easy), uses a QDial and a QLabel to demonstrate the usage of QDial.
When the program initializes the interface, drag the slider position, and the label will display the value of dial.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown in the figure below.
Insert image description here

The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QDial >
5 # include < QLabel >
6 # include < QMainWindow >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明对象*/
	18 QDial * dial;
	19 QLabel * label;
	20
	21 private slots:
	22      /* 槽函数*/
	23 void dialValueChanged( int );


	24
	25
};
26 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置主窗体的位置与大小*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化对象和设置显示位置与大小*/
10 dial = new QDial(this);
11 dial->setGeometry(300, 100, 200, 200);
12
13 /* 设置页长(两个最大刻度的间距)*/
14 dial->setPageStep(10);
15
16 /* 设置刻度可见*/
17 dial->setNotchesVisible(true);
18
19 /* 设置两个凹槽之间的目标像素数*/
20 dial->setNotchTarget(1.00);
21
22 /* 设置dial值的范围*/
23 dial->setRange(0,100);
24
25 /* 开启后可指向圆的任何角度*/
26 //dial->setWrapping(true);
27
28 /* 实例化对象和设置显示位置与大小*/
29 label = new QLabel(this);
30 label->setGeometry(370, 300, 200, 50);
31
32 /* 初始化为0km/h */
33 label->setText("0km/h");
34
35 /* 信号槽连接*/
36 connect(dial, SIGNAL(valueChanged(int)),
37 this, SLOT(dialValueChanged(int)));
38 }
39
40 MainWindow::~MainWindow()
41 {
    
    
42 }
43
44 void MainWindow::dialValueChanged(int val)
45 {
    
    
46 /* QString::number()转换成字符串*/
47 label->setText(QString::number(val) + "km/h");
48 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The result of compiling and running the program is as follows. When the program is initialized, the QDial control is displayed as follows (note that the display format of the QDial control under Windows may be different. The following figure shows the display style of the QDial control under Linux). When you drag the slider with the mouse or press the up, down, left and right arrow keys on the keyboard, the label will display the current "vehicle speed".
Insert image description here
QDial can be used in many situations, such as volume control, car dashboards, Sesame Credit scores, etc. It just requires us to have this creativity and idea, as well as a personal art foundation.

QScrollBar

7.2.12.1 Control introduction
QScrollBar inherits QAbstractSlider. The QScrollBar widget provides a vertical or horizontal scroll bar, allowing users to access portions of a document that are larger than the widget used to display the document. It provides a visual indication of the user's current position in the document and the number of visible documents. Scroll bars are often accompanied by additional controls that allow for more precise navigation (here, browsing to a precise location).
7.2.12.2 Example of usage
Example 19_qscrollbar Create horizontal and vertical scrollbars (difficulty: easy), use the QScrollBar class to instantiate two controls, one is a horizontal scrollbar and the other is a vertical scrollbar, with a label text in the middle to display. (This example only creates an instance, and does not refine the effect (Please note: Generally, QScrollArea is used with other controls for horizontal or vertical scroll bars, and QScrollBar is not used alone to create scroll bars. Some controls "self-contained" scroll bars, such as QListWidget etc., you can
use QScrollArea to set its properties).
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below. The
Insert image description here
specific code in the header file "mainwindow.h" is as follows .

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QScrollBar >
6 # include < QLabel >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明水平滚动条对象*/
	18 QScrollBar * horizontalScrollBar;
	19
	20      /* 声明垂直滚动条对象*/
	21 QScrollBar * verticalScrollBar;
	22
	23      /* 声明标签文本*/
	24 QLabel * label;
	25
};
26 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置主窗体大小,位置*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9       /* 实例化水平滚动条及设置位置大小*/
	10 horizontalScrollBar = new QScrollBar( Qt::Horizontal, this );
	11 horizontalScrollBar->setGeometry( 0, 450, 800, 30 );
	12
	13      /* 实例化垂直滚动条及设置位置大小*/
	14 verticalScrollBar = new QScrollBar( Qt::Vertical, this );
	15 verticalScrollBar->setGeometry( 770, 0, 30, 480 );
	16
	17      /* 实例化,标签文本*/
	18 label = new QLabel( this );
	19      /* 设置文本*/
	20 label->setText( "这是一个测试" );
	21      /* 设置位置大小*/
	22 label->setGeometry( 300, 200, 100, 20 );
	23
}


24
25 MainWindow::~MainWindow()
26
{
    
    
	27
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}

Running effect:
The result of program compilation and running. As shown below, when the program is initialized, the scroll bar control is displayed as follows (note that the display format of the scroll bar control under Windows may be different. The following figure shows the display style of the scroll bar control under Linux).
Insert image description here

QSlider

7.2.13.1 Control introduction
QSlider inherits QAbstractSlider. The QScrollBar class provides a vertical or horizontal slider widget, which is a typical widget used to control bounded values. It allows the user to move a slider handle along a horizontal or vertical groove and converts the handle's position into an integer value within the legal range.
7.2.13.2 Usage
Example 20_qslider Create horizontal and vertical slide bars (Difficulty: Easy) Create two QSlider objects, one is a horizontal slide bar and the other is a vertical slide bar; use a Label to display the current horizontal or vertical slide bar. value. Setting the horizontal slide bar and the horizontal slide bar are related to each other. By sliding the value of one slide bar, the value of the other slide bar will be changed accordingly.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QSlider >
6 # include < QLabel >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明对象*/
	18 QSlider * horizontalSlider;
	19 QSlider * verticalSlider;
	20 QLabel * label;
	21 private slots:
	22      /* 槽函数*/
	23 void horizontalSliderValueChanged( int );


	24 void verticalSliderValueChanged( int );


	25
	26
};
27 # endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 this->setGeometry(0, 0, 800, 480);
7
8 /* 实例化水平滑动条对象*/
9 horizontalSlider = new QSlider(Qt::Horizontal, this);
10
11 /* 设置显示的位置与大小*/
12 horizontalSlider->setGeometry(250, 100, 200, 20);
13
14 /* 设置值范围*/
15 horizontalSlider->setRange(0, 100);
16
17 /* 实例化垂直滑动条对象*/
18 verticalSlider = new QSlider(Qt::Vertical, this);
19
20 /* 设置显示的位置与大小*/
21 verticalSlider->setGeometry(200, 50, 20, 200);
22
23 /* 设置值范围*/
24 verticalSlider->setRange(0, 100);
25
26 /* 实例化标签文本*/
27 label = new QLabel("滑动条值:0", this);
28 label->setGeometry(250, 200, 100, 20);
29
30 /* 信号槽连接*/
31 connect(horizontalSlider, SIGNAL(valueChanged(int)),
32 this, SLOT(horizontalSliderValueChanged(int)));
33 connect(verticalSlider, SIGNAL(valueChanged(int)),
34 this, SLOT(verticalSliderValueChanged(int)));
35
36 }
37
38 MainWindow::~MainWindow()
39 {
    
    
40 }
41
42 void MainWindow::horizontalSliderValueChanged(int val)
43 {
    
    
44 /* 当水平滑动条的值改变时,改变垂直滑动条的值*/
45 verticalSlider->setSliderPosition(val);
46
47 /* 将int类型转变成字符*/
48
49 QString str = "滑动条值:" + QString::number(val);
50
51 /* 显示当前垂直或水平滑动条的值*/
52 label->setText(str);
53
54 }
55
56 void MainWindow::verticalSliderValueChanged(int val)
57 {
    
    
58 /* 当垂直滑动条的值改变时,改变水平滑动条的值*/
59 horizontalSlider->setSliderPosition(val);
60 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. When the program is initialized, the display of the slider control is as follows (note that the display format of the slider control under windows may be different, and the figure below shows the display style of the slider control under linux). The initial value displayed by the Label is 0. When dragging any slider to change the current value, the value of the other slider also changes.
Insert image description here

QKeySequenceEdit

7.2.14.1 Control Introduction
QKeySequenceEdit inherits QWidget. This widget allows the user to select a QKeySequence, which is often used as a shortcut. Recording starts when the widget receives focus and ends one second after the user releases the last key, typically used as a record shortcut.
7.2.14.2 Example of usage
Example 21_qkeysequenceedit custom shortcut keys (difficulty: simple), usually the KeySequenceEdit control records the shortcut keys and uses them with Qt keyboard events. Since the event is mentioned later in the tutorial, it is not used with Qt keyboard events.
Next, use a QKeySequenceEdit control, and then judge whether the input combination key is Ctrl + Q, if so, close the window and exit the program, if not, continue to update the record combination key.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QKeySequenceEdit >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* 声明QKeySequenceEdit对象*/
	17 QKeySequenceEdit * keySequenceEdit;
	18
	19 private slots:
	20      /* 声明槽*/
	21 void KSEKeySequenceChanged( const QKeySequence & );


	22
	23
};
24 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 #include <QDebug>
3
4 MainWindow::MainWindow(QWidget *parent)
5 : QMainWindow(parent)
6 {
    
    
7 /* 主窗体设置位置与大小*/
8 this->setGeometry(0, 0, 800, 480);
9
10 /* 实例化*/
11 keySequenceEdit = new QKeySequenceEdit(this);
12
13 /* 设置位置与大小*/
14 keySequenceEdit->setGeometry(350, 200, 150, 30);
15
16 /* 信号槽连接*/
17 connect(keySequenceEdit,
18 SIGNAL(keySequenceChanged(const QKeySequence &)),
19 this,
20 SLOT(KSEKeySequenceChanged(const QKeySequence &))
21 );
22
23 }
24
25 MainWindow::~MainWindow()
26 {
    
    
27 }
28
29 void MainWindow::KSEKeySequenceChanged(
30 const QKeySequence &keySequence)
31 {
    
    
32 /* 判断输入的组合键是否为Ctrl + Q,如果是则退出程序*/
33 if(keySequence == QKeySequence(tr("Ctrl+Q"))) {
    
    
34 /* 结束程序*/
35 this->close();
36 }else {
    
    
37 /* 打印出按下的组合键*/
38 qDebug()<<keySequence.toString()<<endl;
39 }
40 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. (Note that the display effect may be different under Windows. The picture below shows the result of running under Linux). When the focus is in KeySequenceEdit, press any key or key combination on the keyboard. After one second, KeySequenceEdit will record this/this key combination. , and printed in the output information. The program window will not close until the program presses the Ctrl + Q key combination, ending.
Insert image description here

show widget

Qt Designer provides 10 display widgets in the panel provided by the display widget. In the Qt5 version before Qt5.5, this display widget also had a QWebview widget, which was removed starting from Qt5.6 and replaced by QWebengine, but QWebengine is not displayed in this display widget in the form of a widget.
Insert image description here
(1) Label: label
(2) Text Browser: text browser
(3) Graphics View: graphics view
(4) Calendar Widget: calendar
(5) LCD Number: liquid crystal number
(6) Progress Bar: progress bar
(7) Horizontal Line: Horizontal line
(8) Vertial Line: Vertical line
(9) OpenGL Widget: Open graphics library tool
(10) QQuick Widget: Embedded QML tool
The functions of these sixteen button widgets are introduced as follows:
QLabel provides a text Or a widget for image display. The Label control has appeared in some of the previous sections 4.1 and 4.2. It is only used to display text. In fact, it can also be used to display images.
QCalendarWidget inherits QWidget. The QCalendarWidget class provides a month-based calendar widget that allows the user to select a date. The CalendarWidget widget is initialized with the current month and year, QCalendarWidget also provides several public slots to change the displayed year and month.
QLCDNumber 继承QFrame。QLCDNumber 小部件显示一个类似于lcd 的数字。QLCDNumber 小部件可以显示任意大小的数字。它可以显示十进制、十六进制、八进制或二进制数字。
使用display()插槽很容易连接到数据源,该插槽被重载以接受五种参数类型中的任何一种。
QProgressBar 继承QWidget。QProgressBar 小部件提供了一个水平或垂直的进度条。进度条用于向用户显示操作的进度,并向他们确认应用程序仍在运行。
QFrame 继承QWidget。QFrame 类是有框架的窗口部件的基类,它绘制框架并且调用一个虚函数drawContents()来填充这个框架。这个函数是被子类重新实现的。这里至少还有两个有用的函数:drawFrame()和frameChanged()。
QTextBrowser 继承QTextEdit,QTextBrowser 类提供了一个具有超文本导航的文本浏览器。
该类扩展了QTextEdit(在只读模式下),添加了一些导航功能,以便用户可以跟踪超文本文档中的链接。
QGraphicsView 继承QAbstractScrollArea。QGraphicsView 是图形视图框架的一部分,它提供了基于图元的模型/视图编程。QGraphicsView 在可滚动视图中可视化QGraphicsScene 的内容。
要创建带有几何项的场景,请参阅QGraphicsScene 的文档。
要可视化场景,首先构造一个QGraphicsView 对象,将要可视化的场景的地址传递给QGraphicsView 的构造函数。或者,可以调用setScene()在稍后设置场景。
Text Browser (text browser), Graphics View (graphics view), OpenGL Widget (open graphics library tool), QQuick Widget (embedded QML tool) will not be introduced in this section, among which Text Browser (text browser), GraphicsView ( Graphical View) Browser introduction to the display window in Section 7.4.

QLabel

7.3.1.1 Introduction to Controls
QLabel provides a widget for displaying text or images. The Label control has appeared in the previous sections 7.2.11 and 7.2.12. It is only used to display text. In fact, it can also be used for Display image.
7.3.1.2 Usage examples
Example 22_qlbel Label displays images or text (easy difficulty). Label has appeared in some sections before, but it is only used to display text content. In fact, buttons, widgets, labels, etc. are all Can be used to display images. But buttons are not commonly used to display a single image, because buttons have three states: pressed, released, and hovered. So it is not commonly used to simply display an image.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
In this example, a resource image has been added. If you are not sure how to add a resource image, please refer to Section 7.1.4. The addition is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QLabel >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* 用一个QLabel对象用于显示字符串*/
	17 QLabel * labelString;
	18
	19      /* 用一个QLabel对象用于显示图像*/
	20 QLabel * labelImage;
	21
};
22 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QLabel >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* 用一个QLabel对象用于显示字符串*/
	17 QLabel * labelString;
	18
	19      /* 用一个QLabel对象用于显示图像*/
	20 QLabel * labelImage;
	21
};
22 # endif      /* MAINWINDOW_H */

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. In order to avoid causing the image to be compressed or stretched, the size of the label is set to 452*132 this time, which is set based on the actual size of the image.

Insert image description here

QCalendarWidget

Introduction to controls

QCalendarWidget inherits QWidget. The QCalendarWidget class provides a month-based calendar widget that allows the user to select a date. The CalendarWidget widget is initialized with the current month and year, and QCalendarWidget also provides several public slots to change the displayed year and month.

Usage examples
Example 23_qcalendarwidget Simple use of calendar (difficulty: easy), this example simply uses the calendar control to achieve certain effects. Use a CalendarWidget control, a Label to display the date selected in the current calendar, and a pushButton button. Click the pushButton button to return to the current system date.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QCalendarWidget >
6 # include < QPushButton >
7 # include < QLabel >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 声明QCalendarWidget,QPushButton,QLabel对象*/
	19 QCalendarWidget * calendarWidget;
	20 QPushButton * pushButton;
	21 QLabel * label;
	22
	23 private slots:
	24      /* 槽函数*/
	25 void calendarWidgetSelectionChanged();


	26 void pushButtonClicked();


	27
	28
};
29 # endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置位置与大小,下同*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 对象实例化设置显示的位置与大小*/
10 calendarWidget = new QCalendarWidget(this);
11 calendarWidget->setGeometry(200, 20, 400, 300);
12
13 QFont font;
14 /* 设置日历里字体的大小为10像素*/
15 font.setPixelSize(10);
16 calendarWidget->setFont(font);
17
18 /* 对象实例化设置显示的位置与大小*/
19 pushButton = new QPushButton("回到当前日期",this);
20 pushButton->setGeometry(200, 350, 100, 30);
21
22 /* 对象实例化设置显示的位置与大小*/
23 label = new QLabel(this);
24 label->setGeometry(400, 350, 400, 30);
25 QString str = "当前选择的日期:"
26 + calendarWidget->selectedDate().toString();
27 label->setText(str);
28
29 /* 信号槽连接*/
30 connect(calendarWidget, SIGNAL(selectionChanged()),
31 this, SLOT(calendarWidgetSelectionChanged()));
32 connect(pushButton, SIGNAL(clicked()),
33 this, SLOT(pushButtonClicked()));
34 }
35
36 MainWindow::~MainWindow()
37 {
    
    
38 }
39
40 void MainWindow::calendarWidgetSelectionChanged()
41 {
    
    
42 /* 当日历点击改变当前选择的期时,更新Label的显示内容*/
43 QString str = "当前选择的日期:"
44 + calendarWidget->selectedDate().toString();
45 label->setText(str);
46 }
47
48 void MainWindow::pushButtonClicked()
49 {
    
    
50 /* 设置当前选定的日期为系统的QDate */
51 calendarWidget->setSelectedDate(QDate::currentDate());
52 }
53

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. When the program is running, you can change the currently selected date by clicking the mouse or keyboard, and the label will change to the currently selected date. When you click the Return to Current Date button, the calendar will change the currently selected date and The currently selected date changes to the system's current date. Expansion: You can use the calendar to set birthdays, date reminders, etc., and you can also create a gorgeous system calendar interface, etc.
Insert image description here

QLCDNumber

7.3.3.1 Control introduction
QLCDNumber inherits QFrame. The QLCDNumber widget displays a number similar to an lcd.
The QLCDNumber widget can display numbers of any size. It can display decimal, hexadecimal, octal or binary numbers. Connecting to a data source is easy using the display() slot, which is overloaded to accept any of the five parameter types.
7.3.3.2 Usage examples
Example 24_qlcdnumber, LCDNumber clock (difficulty: easy), uses an LCDNumber control to display the clock, and a timer to regularly update the LCDNumber time.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QMainWindow >
6 # include < QLCDNumber >
7 # include < QTimer >
8 # include < QTime >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19      /* 声明QLCDNumber对象*/
	20 QLCDNumber * lcdNumber;
	21
	22      /* 声明QTimer对象*/
	23 QTimer * timer;
	24
	25 private slots:
	26      /* 槽函数*/
	27 void timerTimeOut();


	28
	29
};
30 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置主窗体的大小与位置*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化与设置显示的位置大小*/
10 lcdNumber = new QLCDNumber(this);
11 lcdNumber->setGeometry(300, 200, 200, 50);
12
13 /* 设置显示的位数8位*/
14 lcdNumber->setDigitCount(8);
15 /* 设置样式*/
16 lcdNumber->setSegmentStyle(QLCDNumber::Flat);
17
18 /* 设置lcd显示为当前系统时间*/
19 QTime time = QTime::currentTime();
20
21 /* 设置显示的样式*/
22 lcdNumber->display(time.toString("hh:mm:ss"));
23
24 timer = new QTimer(this);
25 /* 设置定时器1000毫秒发送一个timeout()信号*/
26 timer->start(1000);
27
28 /* 信号槽连接*/
29 connect(timer, SIGNAL(timeout()), this,
30 SLOT(timerTimeOut()));
31
32 }
33
34 MainWindow::~MainWindow()
35 {
    
    
36 }
37
38 void MainWindow::timerTimeOut()
39 {
    
    
40 /* 当定时器计时1000毫秒后,刷新lcd显示当前系统时间*/
41 QTime time = QTime::currentTime();
42 /* 设置显示的样式*/
43 lcdNumber->display(time.toString("hh:mm:ss"));
44 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The results of program compilation and running are as follows. After the program is run, you can see that the time is the current system time, and the LCDNumber clock displays the system clock and is running.
Insert image description here

QProgressBar

7.3.4.1 Control introduction
QProgressBar inherits QWidget. The QProgressBar widget provides a horizontal or vertical progress bar. Progress bars are used to show the user the progress of an operation and to confirm to them that the application is still running.
7.3.4.2 Usage examples
Example 25_qprogressbar, mobile phone battery charging. Use a QProgressBar to simulate mobile phone battery charging.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
In this example, a battery background image resource image has been added. If you are not sure how to add a resource image, please refer to Section 7.1.4. The addition is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QProgressBar >
6 # include < QTimer >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 声明对象*/
	18 QProgressBar * progressBar;
	19 QTimer * timer;
	20
	21      /* 用于设置当前QProgressBar的值*/
	22 int value;
	23
	24 private slots:
	25      /* 槽函数*/
	26 void timerTimeOut();


	27
	28
};
29 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6                                                       /* 设置主窗体位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9 progressBar = new QProgressBar( this );
	10 progressBar->setGeometry( 300, 200, 200, 60 );
	11
	12                                                      /*样式表设置,常用使用setStyleSheet来设置样式(实现界面美化的功能),
	                                                         * 13 * 具体可参考styleSheet */
	14 progressBar->setStyleSheet(
		15 "QProgressBar{border:8px solid #FFFFFF;"
		16 "height:30;"
		17 "border-image:url(:/images/battery.png);"    /* 背景图片 */
		18 "text-align:center;"                         /* 文字居中 */
		19 "color:rgb(255,0,255);"
		20 "font:20px;"                                 /* 字体大小为20px */
		21 "border-radius:10px;}"
		22 "QProgressBar::chunk{"
		23 "border-radius:5px;"                         /* 斑马线圆角 */
		24 "border:1px solid black;"                    /* 黑边,默认无边 */
		25 "background-color:skyblue;"
		26 "width:10px;margin:1px;}"                    /* 宽度和间距 */
		27 );
	28
	29                                                      /* 设置progressBar的范围值*/
	30 progressBar->setRange( 0, 100 );
	31                                                      /* 初始化value为0 */
	32 value = 0;
	33                                                      /* 给progressBar设置当前值*/
	34 progressBar->setValue( value );
	35                                                      /* 设置当前文本字符串的显示格式*/
	36 progressBar->setFormat( "充电中%p%" );
	37
	38                                                      /* 定时器实例化设置每100ms发送一个timeout信号*/
	39 timer = new QTimer( this );
	40 timer->start( 100 );
	41
	42                                                      /* 信号槽连接*/
	43 connect( timer, SIGNAL( timeout() ),
		    44 this, SLOT( timerTimeOut() ) );
	45
}


46
47 MainWindow::~MainWindow()
48
{
    
    
	49
}


50
51 void MainWindow::timerTimeOut()
52
{
    
    
	53      /* 定显示器时间到,value值自加一*/
	54 value++;
	55 progressBar->setValue( value );
	56      /* 若value值大于100,令value再回到0 */
	57 if ( value > 100 )
		58 value = 0;
	59
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The results of program compilation and running are as follows. After the program runs, it can be seen that under the action of the timer, the battery has been charging, charging to 100%, and then returning to 0% to recharge. QProgressBar is generally used to represent progress, such as copying progress, opening, loading progress, etc.
Insert image description here

QFrame

7.3.5.1 Control introduction
QFrame inherits QWidget. The QFrame class is the base class for framed widgets. It draws the frame and calls a virtual function drawContents() to fill the frame. This function is reimplemented by subclasses. There are at least two more useful functions here: drawFrame() and frameChanged().
QPopupMenu uses this to "raise" the menu above the surrounding screen. QProgressBar has a "sunken" appearance.
QLabel has a flat appearance. These framed widgets can be changed.
QFrame::Shape This enumeration type defines the shape used by QFrame's frame. Currently defined effects are:
NoFrame - QFrame doesn't draw anything
Box - QFrame draws a box around its content
Panel - QFrame draws a flat panel making the content look raised or sunken
WinPanel - like Panel, but QFrame draws 3D effects work the same way as in Microsoft Windows 95 (and others)
ToolBarPanel - QFrame calls QStyle::drawToolBarPanel()
MenuBarPanel - QFrame calls QStyle::drawMenuBarPanel()
HLine - QFrame draws a horizontal line, but does not frame anything (
VLine - QFrame draws a vertical line but does not frame anything (useful as a divider) StyledPanel
- QFrame calls QStyle::drawPanel()
PopupPanel - QFrame calls QStyle::drawPopupPanel().
The shadow styles are:
Plain is drawn using the foreground color of the palette (without any three-dimensional effect).
Raised draws three-dimensional raised lines using the light and dark colors of the current color group.
Sunken draws three-dimensional sunken lines using the light and dark colors of the current color group.

7.3.5.2 Usage examples
Example 26_qframe, horizontal/vertical lines (difficulty: easy), define two QFrame objects, and set them to one horizontal style and one vertical style after instantiation. In fact, the Horizontal Line/Vertical Line in Display Widgets are controls that have been encapsulated by QFrame. Different effects can also be achieved through the following examples.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QFrame >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* 声明对象*/
	17 QFrame * hline;
	18 QFrame * vline;
	19
	20
};
21 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置主窗体的显示位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9       /* 实例化*/
	10 hline = new QFrame( this );
	11      /* 确定起始点,设置长和宽,绘制距形*/
	12 hline->setGeometry( QRect( 200, 100, 400, 40 ) );
	13
	14      /* 设置框架样式为Hline,水平,可设置为其他样式例如Box,
	         * 15 * 由于是样式选择HLine,所以只显示一条水平直线
	         * 16 */
	17 hline->setFrameShape( QFrame::HLine );
	18      /* 绘制阴影*/
	19 hline->setFrameShadow( QFrame::Sunken );
	20
	21      /* 实例化*/
	22 vline = new QFrame( this );
	23      /* 确定起始点,设置长和宽,绘制距形*/
	24 vline->setGeometry( QRect( 300, 100, 2, 200 ) );
	25
	26      /* 设置框架样式为Vline,垂直,可设置为其他样式例如Box,
	         * 27 * 由于是样式选择Vline,所以只显示一条垂直直线
	         * 28 */
	29 vline->setFrameShape( QFrame::VLine );
	30      /* 绘制阴影*/
	31 vline->setFrameShadow( QFrame::Sunken );
	32
}


33
34 MainWindow::~MainWindow()
35
{
    
    
	36
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. A vertical line and a horizontal line appear in the center of the window. You can use QFrame to draw some nice-looking borders to beautify the interface. The QFrame class is the base class for all frame widgets, so common controls like QLabel can also be set to unique border styles.
Insert image description here

Browser showing widgets

QTextBrowser

7.4.1.1 Control Introduction
QTextBrowser inherits QTextEdit, and the QTextBrowser class provides a text browser with hypertext navigation.
This class extends QTextEdit (in read-only mode), adding some navigation functionality so that users can follow links in hypertext documents.
7.4.1.2 Usage examples
Example 27_qtextbrowser, a simple text browser (difficulty: easy), this example designs a text browser program that can open and display txt, html and other files. This section also uses QAction, menu bar, opening and processing of learning files, etc.
The new routine can inherit the QMainWindow class by default. Check mainwindow.ui because we want to add buttons to the toolbar to open files and other operations. The new project is completed as follows.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QTextBrowser >
6
7 QT_BEGIN_NAMESPACE
8 namespace Ui {
    
     class MainWindow; }
9 QT_END_NAMESPACE
10
11 class MainWindow : public QMainWindow
	12 {
    
    
	13 Q_OBJECT
	14
	15 public:
	16 MainWindow( QWidget *parent = nullptr );
	17 ~MainWindow();
	18
	19 private:
	20 Ui::MainWindow * ui;
	21      /* 声明对象*/
	22 QTextBrowser * textBrowser;
	23 QAction * openAction;
	24
	25 private slots:
	26      /* 槽函数*/
	27 void openActionTriggered();


	28
};
29 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include "ui_mainwindow.h"
3 /* 窗口对话框与文本流*/
4 # include < QFileDialog >
5 # include < QTextStream >
6
7 MainWindow::MainWindow( QWidget *parent )
8 : QMainWindow( parent )
	9, ui( new Ui::MainWindow )
	10
{
    
    
	11 ui->setupUi( this );
	12      /* 设置主窗体位置与大小*/
	13 this->setGeometry( 0, 0, 800, 480 );
	14
	15      /* 将窗口标题设置为文本浏览器*/
	16 this->setWindowTitle( "文本浏览器" );
	17
	18      /* 实例化*/
	19 textBrowser = new QTextBrowser( this );
	20      /* 将文本浏览器窗口居中*/
	21 this->setCentralWidget( textBrowser );
	22
	23      /* 实例化*/
	24 openAction = new QAction( "打开", this );
	25      /* ui窗口自带有menubar(菜单栏)、mainToolbar(工具栏)与
	         * 26 * statusbar(状态栏)
	         * 27 * menuBar是ui生成工程就有的,所以可以在menubar里添加
	         * 28 * 我们的QActiont等,如果不需要menubar,可以在ui设计
	         * 29 * 窗口里,在右则对象里把menubar删除,再自己重新定义自己的
	         * 30 * 菜单栏
	         * 31 */
	32      /* 将动作添加到菜单栏*/
	33 ui->menubar->addAction( openAction );
	34
	35      /* 信号槽连接*/
	36 connect( openAction, SIGNAL( triggered() ),
		    37 this, SLOT( openActionTriggered() ) );
	38
	39
}


40
41 MainWindow::~MainWindow()
42
{
    
    
	43 delete ui;
	44
}


45
46 void MainWindow::openActionTriggered()
47
{
    
    
	48      /* 调用系统打开文件窗口,过滤文件名*/
	49 QString fileName = QFileDialog::getOpenFileName(
		50 this, tr( "打开文件" ), "",
		51 tr( "Files(*.txt *.cpp *.h *.html *.htm)" )
		52 );
	53 QFile myFile( fileName );
	54      /* 以只读、文本方式打开,若打开失败,则返回*/
	55 if ( !myFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
		56 return;
	57
	58      /* 用QTextStream对象接收*/
	59 QTextStream in( &myFile );
	60
	61      /* 读取全部数据*/
	62 QString myText = in.readAll();
	63
	64      /* 判断打开文件的后缀,如果是html格式的则设置文本浏览器为html格式*/
	65 if ( fileName.endsWith( "html" ) || fileName.endsWith( "htm" ) )
	{
    
    
		66 textBrowser->setHtml( myText );
		67
	} else {
    
    
		68 textBrowser->setPlainText( myText );
		69
	}
	70
	71 /* ui窗口自带有statusbar(状态栏),设置打开的文件名*/
	72 ui->statusbar->showMessage( "文件名:" + fileName );
	73
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. After clicking Open on the menu bar, the system defaults to the recently opened location. Select any file that can be opened. This time, the mainwindow.cpp file in the project is opened, and the result is as shown in the figure below. According to the above example, you can expand and build your own text browser, such as adding a close action on the menu bar, etc., and adding font color, background color, and font zoom in and out in the toolbar, etc., which can be expanded by yourself . (Note: After testing,
the Qt program of Ubuntu16 is abnormal and the menu bar cannot be seen, so the "Open" button cannot be seen. Ubuntu18 displays normally.)

Insert image description here

QGraphicsView

Preface to this section:
Here we will briefly introduce the introduction and common interfaces of the QGraphicsView framework class. In fact, this framework is too complex and we cannot fully demonstrate it in this section. Let us quickly understand the QGraphicsView graphics view framework class. Bar!
7.4.2.1 Control introduction
QGraphicsView inherits QAbstractScrollArea. QGraphicsView is part of the Graphics View Framework, which provides primitive-based model/view programming. QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable view.
To create a scene with geometry items, see the documentation for QGraphicsScene.
To visualize a scene, first construct a QGraphicsView object and pass the address of the scene to be visualized to the QGraphicsView constructor. Alternatively, you can call setScene() to set the scene later.
7.4.2.2 Usage examples
Example 28_qgraphicsview, a simple image browser (difficulty: easy), this example designs an image browser program and changes it into an image browser based on the previous section 1.
The new routine can inherit the QMainWindow class by default. Check mainwindow.ui because we want to add buttons to the toolbar to open files and other operations. The new project is completed as follows.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QGraphicsView >
6
7 QT_BEGIN_NAMESPACE
8 namespace Ui {
    
     class MainWindow; }
9 QT_END_NAMESPACE
10
11 class MainWindow : public QMainWindow
	12 {
    
    
	13 Q_OBJECT
	14
	15 public:
	16 MainWindow( QWidget *parent = nullptr );
	17 ~MainWindow();
	18
	19 private:
	20 Ui::MainWindow * ui;
	21      /* 声明对象*/
	22 QGraphicsView * graphicsView;
	23 QGraphicsScene * graphicsScene;
	24 QAction * openAction;
	25
	26 private slots:
	27      /* 槽函数*/
	28 void openActionTriggered();


	29
	30
};
31 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 #include "ui_mainwindow.h"
3 #include <QFileDialog>
4
5 MainWindow::MainWindow(QWidget *parent)
6 : QMainWindow(parent)
7 , ui(new Ui::MainWindow)
8 {
    
    
9 ui->setupUi(this);
10 /* 设置主窗体大小*/
11
12 this->setGeometry(0, 0, 800, 480);
13 /* 将窗口标题设置为图像浏览器*/
14 this->setWindowTitle("图像浏览器");
15
16 /* 实例化图形视图对象*/
17 graphicsView = new QGraphicsView(this);
18 /* 将图像浏览器窗口居中*/
19 this->setCentralWidget(graphicsView);
20
21 /* 实例化场景对象*/
22 graphicsScene = new QGraphicsScene(this);
23
24 /* 在QGraphicsView设置场景*/
25 graphicsView->setScene(graphicsScene);
26
27 /* 将动作添加到菜单栏*/
28 openAction = new QAction("打开",this);
29 ui->menubar->addAction(openAction);
30
31 /* 信号槽连接*/
32 connect(openAction, SIGNAL(triggered()),
33 this, SLOT(openActionTriggered()));
34 }
35
36 MainWindow::~MainWindow()
37 {
    
    
38 delete ui;
39 }
40
41 void MainWindow::openActionTriggered()
42 {
    
    
43 /*调用系统打开文件窗口,设置窗口标题为“打开文件”,过滤文件名*/
44 QString fileName = QFileDialog::getOpenFileName(
45 this,tr("打开文件"), "",
46 tr("Files(*.png *.jpg *.bmp)")
47 );
48 /* 定义QPixmap对象,指向fileName */
49 QPixmap image(fileName);
50 /* 将image用scaled来重新设置长宽为graphicsView的长宽,
51 * 保持纵横比等
52 */
53
54 /* 假若用户没选择文件,则返回*/
55 if(image.isNull())
56 return;
57 image = image.scaled(graphicsView->width(),
58 graphicsView->height(),
59 Qt::KeepAspectRatio,
60 Qt::FastTransformation
61 );
62 /* 在添加场景内容前,先清除之前的场景内容*/
63 graphicsScene->clear();
64 /* 添加场景内容image */
65 graphicsScene->addPixmap(image);
66 /* ui窗口自带有statusBar(状态栏),设置打开的文件名*/
67 ui->statusbar->showMessage("文件名:" + fileName);
68 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. After clicking to open the menu bar, the system defaults to the recently opened location. Select any open picture. (Note: The pictures shown in this example have been placed in the project directory).
Insert image description here

layout management

Qt provides a very rich layout class. The basic layout management classes include: QBoxLayout, QGridLayout, QFormLayout and QStackedLayout. These classes all inherit from QLayout, and they all come from QObject (not QWidget). Create more complex layouts that can be nested within each other.
Among them, QBoxLayout provides horizontal and vertical layout management; QFormLayout provides layout management that arranges input components and labels in groups; QGridLayout provides layout management in the form of grid; QStackedLayout provides a set of laid out components that can be Distribution display.
Their inheritance relationship is shown in the figure below.
Insert image description here
Next we will learn the 4 layouts in the Layouts group, as shown below.
Insert image description here
The names of each control are explained in turn as follows.
(1) Vertiacl Layout: vertical layout
(2) Horizontal Layout: horizontal layout
(3) Grid Layout: grid layout
(4) Form Layout: form layout
QBoxLayout inherits QLayout. The QBoxLayout class provides for arranging child widgets horizontally or vertically. QBoxLayout takes the space obtained from its parent layout or from parentWidget(), divides it into a column of boxes, and makes each managed widget fill a box.
QGridLayout inherits QLayout. QGridLayout takes the available space (via its parent layout or parentWidget()), divides it into rows and columns, and places each widget it manages into the correct cell. Since the components in the grid layout manager will also change as the window is stretched, it is also necessary to set the proportion coefficient between the components. Different from QBoxLayout, the grid layout manager also needs to set rows and columns separately. proportional coefficient.
QFormLayout inherits QLayout. The QFormLayout class manages a form of input widgets and their associated labels. QFormLayout is a convenience layout class that layouts its subclasses in a two-column format. The left column consists of labels and the right column consists of "field" widgets (QLineEdit (line editor), QSpinBox (spin box, etc.)). Usually the setRowWrapPolicy(RowWrapPolicy policy) interface function is used to set the line wrapping policy of the layout for layout, etc.

QBoxLayout

7.5.1.1 Control introduction
QBoxLayout inherits QLayout. The QBoxLayout class provides horizontal or vertical arrangement of child widgets. QBoxLayout takes the space obtained from its parent layout or from parentWidget(), divides it into a column of boxes, and makes each managed widget fill a box.
7.5.1.2 Usage examples
Example 29_qboxlayout, vertical or horizontal layout (difficulty: easy), use several buttons, set them to vertical arrangement and horizontal arrangement, and set some of their properties.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown in the figure below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QHBoxLayout >
6 # include < QVBoxLayout >
7 # include < QPushButton >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 声明按钮对象数组*/
	19 QPushButton * pushButton[6];
	20
	21      /* 定义两个widget,用于容纳排布按钮*/
	22 QWidget * hWidget;
	23 QWidget * vWidget;
	24
	25      /* QHBoxLayout与QVBoxLayout对象*/
	26 QHBoxLayout * hLayout;
	27 QVBoxLayout * vLayout;
	28
	29
};
30 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QList >
3
4 MainWindow::MainWindow( QWidget *parent )
5 : QMainWindow( parent )
	6
{
    
    
	7       /* 设置主窗口的位置与大小*/
	8 this->setGeometry( 0, 0, 800, 480 );
	9
	10      /* 实例化与设置位置大小*/
	11 hWidget = new QWidget( this );
	12 hWidget->setGeometry( 0, 0, 800, 240 );
	13
	14 vWidget = new QWidget( this );
	15 vWidget->setGeometry( 0, 240, 800, 240 );
	16
	17 hLayout	= new QHBoxLayout();
	18 vLayout	= new QVBoxLayout();
	19
	20                      /* QList<T>是Qt的一种泛型容器类。
	                         * 21 * 它以链表方式存储一组值,
	                         * 22 * 并能对这组数据进行快速索引
	                         * 23 */
	24 QList <QString>list;
	25                      /* 将字符串值插入list */
	26 list << "one" << "two" << "three" << "four" << "five" << "six";
	27
	28                      /* 用一个循环实例化6个按钮*/
	29 for ( int i = 0; i < 6; i++ )
	{
    
    
		30 pushButton[i] = new QPushButton();
		31 pushButton[i]->setText( list[i] );
		32 if ( i < 3 )
		{
    
    
			33      /* 将按钮添加至hLayout中*/
			34 hLayout->addWidget( pushButton[i] );
			35
		} else {
    
    
			36      /* 将按钮添加至vLayout中*/
			37 vLayout->addWidget( pushButton[i] );
			38
		}
		39
	}
	40                      /* 设置间隔为50 */
	41 hLayout->setSpacing( 50 );
	42
	43                      /* hWidget与vWidget的布局设置为hLayout/vLayout */
	44 hWidget->setLayout( hLayout );
	45 vWidget->setLayout( vLayout );
	46
}


47
48 MainWindow::~MainWindow()
49
{
    
    
	50
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. You can see that 3 horizontally arranged buttons have been added to the hWidget, and 3 vertically arranged buttons have been added to the vWidget.
Insert image description here

QGridLayout

7.5.2.1 Control Introduction
The QGridLayout class provides a grid (two-dimensional) management interface components in the layout manager. Taking the button components as an example, the coordinates of their corresponding grids are as follows, which are similar to two-dimensional arrays .
Insert image description here
QGridLayout inherits QLayout. QGridLayout takes the available space (via its parent layout or parentWidget()), divides it into rows and columns, and puts each widget it manages into the correct cell. Since the components in the grid layout manager will also change as the window is stretched, it is also necessary to set the proportional coefficient between the components. Unlike QBoxLayout, the grid layout manager also needs to set the rows and columns separately. proportional coefficient.
7.5.2.2 Usage example
Example 30_qgridlayout, grid layout (difficulty: easy), use several buttons, set them to grid layout, set their row, column scale factor (stretch factor), and set some of their Attributes.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QGridLayout >
6 # include < QPushButton >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15 private:
	16
	17      /* 声明widget窗口部件,用于容纳下面4个pushButton按钮*/
	18 QWidget * gWidget;
	19
	20      /* 声明QGridLayout对象*/
	21 QGridLayout * gridLayout;
	22
	23      /* 声明pushButton按钮数组*/
	24 QPushButton * pushButton[4];
	25
	26
};
27 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6               /* 设置位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9               /* 实例化*/
	10 gWidget = new QWidget( this );
	11              /* 设置gWidget居中央*/
	12 this->setCentralWidget( gWidget );
	13
	14 gridLayout = new QGridLayout();
	15              /* QList链表,字符串类型*/
	16 QList <QString> list;
	17 list << "按钮1" << "按钮2" << "按钮3" << "按钮4";
	18 for ( int i = 0; i < 4; i++ )
	{
    
    
		19 pushButton[i] = new QPushButton();
		20 pushButton[i]->setText( list[i] );
		21      /* 设置最小宽度与高度*/
		22 pushButton[i]->setMinimumSize( 100, 30 );
		23      /* 自动调整按钮的大小*/
		24 pushButton[i]->setSizePolicy(
			25 QSizePolicy::Expanding,
			26 QSizePolicy::Expanding
			27 );
		28 switch ( i )
		{
    
    
			29 case 0:
			30 /* 将pushButton[0]添加至网格的坐标(0,0),下同*/
			31 gridLayout->addWidget( pushButton[i], 0, 0 );
			32 break;
			33 case 1:
			34 gridLayout->addWidget( pushButton[i], 0, 1 );
			35 break;
			36 case 2:
			37 gridLayout->addWidget( pushButton[i], 1, 0 );
			38 break;
			39 case 3:
			40 gridLayout->addWidget( pushButton[i], 1, 1 );
			41 break;
			42 default:
			43 break;
			44
		}
		45
	}
	46      /* 设置第0行与第1行的行比例系数*/
	47 gridLayout->setRowStretch( 0, 2 );
	48 gridLayout->setRowStretch( 1, 3 );
	49
	50      /* 设置第0列与第1列的列比例系数*/
	51 gridLayout->setColumnStretch( 0, 1 );
	52 gridLayout->setColumnStretch( 1, 3 );
	53
	54      /* 将gridLayout设置到gWidget */
	55 gWidget->setLayout( gridLayout );
	56
}


57
58 MainWindow::~MainWindow()
59
{
    
    
	60
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. You can see that 4 buttons have been added to the gWidget. Because the coefficient ratio (stretch factor) of rows and columns is set, the buttons you see are displayed in proportion to the coefficient ratio.
Insert image description here

QFormLayout

7.5.3.1 Control introduction
QFormLayout inherits QLayout. The QFormLayout class manages a form for input widgets and their associated labels. QFormLayout is a convenience layout class that lays out its subclasses in two columns. The left column consists of labels and the right column consists of "field" widgets (QLineEdit (line editor), QSpinBox (spinbox, etc.)). Usually use the setRowWrapPolicy (RowWrapPolicy policy) interface function to set the line wrapping policy of the layout for layout and so on.
7.5.3.2 Usage example
Example 31_qformlayout, form layout (difficulty: easy), will use addRow(const QString &labelText, QWidget *field) to create a QLabel and QWidget widget with given text, and they are partnership.
Simple demonstration of the use of form layout.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 #ifndef MAINWINDOW_H
2 #define MAINWINDOW_H
3
4 #include <QMainWindow>
5 #include <QFormLayout>
6 #include <QLineEdit>
7
8 class MainWindow : public QMainWindow
9 {
    
    
10 Q_OBJECT
11
12 public:
13 MainWindow(QWidget *parent = nullptr);
14 ~MainWindow();
15 private:
16 /* widget对象*/
17 QWidget *fWidget;
18
19 /* 用于输入用户名*/
20 QLineEdit *userLineEdit;
21
22 /* 用于输入密码*/
23 QLineEdit *passwordLineEdit;
24
25 /* 声明QFormLayout对象*/
26 QFormLayout *formLayout;
27 };
28 #endif // MAINWINDOW_H

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置位置与大小*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化及设置位置与大小,下同*/
10 fWidget = new QWidget(this);
11 fWidget->setGeometry(250, 100, 300, 200);
12
13 userLineEdit = new QLineEdit();
14 passwordLineEdit = new QLineEdit();
15
16 formLayout = new QFormLayout();
17
18 /* 添加行*/
19 formLayout->addRow("用户名:", userLineEdit);
20 formLayout->addRow("密码:", passwordLineEdit);
21
22 /* 设置水平垂直间距*/
23 formLayout->setSpacing(10);
24
25 /* 设置布局外框的宽度*/
26 formLayout->setMargin(20);
27
28 /* 将formLayout布局到fWidget */
29 fWidget->setLayout(formLayout);
30 }
31
32 MainWindow::~MainWindow()
33 {
    
    
34 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The results of program compilation and running are as follows. You can see that two lines have been added to fWidget, and their spacing and width from the border have been set. Compared with the QGirdLayout layout, the QFomLayout layout is more suitable for layout patterns with fewer rows and columns. If it is a multi-row multi-column layout, you should use the QGirdLayout layout.
Insert image description here

space separation

Space spacer group (Spacers), as shown in the figure below
Insert image description here
(1) Horizontal Spacer: horizontal spacer
(2) Vertical Spacer: vertical spacer
QSpacerItem inherits QLayoutItem. The QSpacerItem class provides white space (space separation) in the layout. So QSpacerItem is used in layout. It includes Horizontal Spacer (horizontal spacer) and Vertical Spacer (vertical spacer).

QSpacerItem

7.6.1.1 Control introduction
QSpacerItem inherits QLayoutItem. The QSpacerItem class provides white space (space separation) in the layout. So QSpacerItem is used in layout.
7.6.1.2 Usage examples
Example 32_qspaceritem, space spacing (difficulty: normal), using 4 buttons, adding vertical spacing and button 1 to the vertical layout, and adding buttons 2~4 and horizontal spacing to the horizontal layout. Simple demonstration of how to use space interval layout. The spatial interval part is analyzed in the program running results.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here

The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QPushButton >
6 # include < QSpacerItem >
7 # include < QBoxLayout >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 按钮对象数组*/
	19 QPushButton * bt[4];
	20      /* 垂直间隔*/
	21 QSpacerItem * vSpacer;
	22      /* 水平间隔*/
	23 QSpacerItem * hSpacer;
	24      /* 声明一个widget用来存放布局的内容*/
	25 QWidget * widget;
	26      /* 主布局对象*/
	27 QHBoxLayout * mainLayout;
	28      /* 垂直布局对象*/
	29 QVBoxLayout * vBoxLayout;
	30      /* 水平布局对象*/
	31 QHBoxLayout * hBoxLayout;
	32
	33
};
34 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置主窗体显示位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9 widget = new QWidget( this );
	10      /* 居中widget */
	11 this->setCentralWidget( widget );
	12
	13      /* 实例化对象*/
	14 vSpacer = new QSpacerItem( 10, 10,
				      15 QSizePolicy::Minimum,
				      16 QSizePolicy::Expanding
				      17 );
	18 hSpacer = new QSpacerItem( 10, 10,
				      19 QSizePolicy::Expanding,
				      20 QSizePolicy::Minimum
				      21 );
	22
	23 vBoxLayout	= new QVBoxLayout();
	24 hBoxLayout	= new QHBoxLayout();
	25 mainLayout	= new QHBoxLayout();
	26
	27                      /* 在vBoxLayout添加垂直间隔*/
	28 vBoxLayout->addSpacerItem( vSpacer );
	29
	30 QList <QString>list;
	31                      /* 将字符串值插入list */
	32 list << "按钮1" << "按钮2" << "按钮3" << "按钮4";
	33                      /* 用一个循环实例化4个按钮*/
	34 for ( int i = 0; i < 4; i++ )
	{
    
    
		35 bt[i] = new QPushButton();
		36 bt[i]->setText( list[i] );
		37 if ( i == 0 )
		{
    
    
			38      /* 按钮1,设置为100*100 */
			39 bt[i]->setFixedSize( 100, 100 );
			40      /* 在vBoxLayout添加按钮1 */
			41 vBoxLayout->addWidget( bt[i] );
			42
		} else {
    
    
			43      /* 按钮2~4,设置为60*60 */
			44 bt[i]->setFixedSize( 60, 60 );
			45      /* 在hBoxLayout添加按钮2~4 */
			46 hBoxLayout->addWidget( bt[i] );
			47
		}
		48
	}
	49                      /* 在hBoxLayout添加水平间隔*/
	50 hBoxLayout->addSpacerItem( hSpacer );
	51
	52                      /* 在主布局里添加垂直布局*/
	53 mainLayout->addLayout( vBoxLayout );
	54                      /* 在主布局里添加水平布局*/
	55 mainLayout->addLayout( hBoxLayout );
	56
	57                      /* 设置部件间距*/
	58 mainLayout->setSpacing( 50 );
	59                      /* 将主布局设置为widget的布局*/
	60 widget->setLayout( mainLayout );
	61
	62
}


63
64 MainWindow::~MainWindow()
65
{
    
    
	66
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows: vertical space intervals and button 1 are added to the vertical layout, and buttons 2~4 and horizontal space intervals are added to the horizontal layout.
Insert image description here
The diagram is as follows:
Insert image description here

container

The names of each control in Containers
Insert image description here
are explained as follows.
(1) Group Box: Group box
(2) Scroll Area: Scroll area
(3) Tool Box: Tool box
(4) Tab Widget: Label widget
(5) Stacked WIdget: Stacked widget
(6) Frame: Frame
(7 ) Widget: Widget
(8) MDI Area: MDI Area
(9) Dock Widget: Dock form widget.
The explanations of various containers are as follows:
QGroupBox inherits QWidget. QGroupBox provides support for building group boxes. A group box usually has a border and a title bar and is used as a container component in which various widgets can be arranged. It can be used as a container for a group of controls during layout, but it should be noted that layout controls (such as QBoxLayout) are usually used internally for layout. Group boxes also provide keyboard shortcuts that move keyboard focus to a subcomponent of the group box.
QScrollArea inherits QAbstractScrollArea. The scroll area is used to display the content of the child widget in the frame. If the widget exceeds the size of the frame, the view has scroll bars so that the entire area of ​​the child widget can be viewed.
QToolBox inherits QFrame. The QToolBox class provides a list of tab widget items. A toolbox is a widget that displays one column of tabs on top of another column, with the current item displayed below the current tab. Each tab has an index position in the tab column. The tab's item is a QWidget.
QTabWidget inherits QWidget. The abWidget class provides a set of tabbed (multi-page) widgets. QTabWidget is mainly used for page display, each page has an interface, and many interfaces share a common area, which saves the interface size and displays more information for users very conveniently.
QStackedWidget inherits QFrame. The QStackedWidget class provides a widget stack in which only one widget can be seen at a time, similar to QQ's settings panel. QStackedWidget can be used to create user interfaces similar to those provided by QTabWidget. It is a convenience layout widget built on top of the QStackedLayout class. Often used with QListWidget, the effect is as shown in the figure below, the left is the QListWidget list, and the right is QStackedWidget. They are generally connected with
signal slots. By clicking on the QListWidget list on the left and connecting with signal slots, the QStackedWidget on the right can display different content, one widget at a time.
QWidget 类是所有用户界面对象的基类(如QLabel 类继承于QFrame 类,而QFrame 类又继承于QWidget 类)。Widget 是用户界面的基本单元:它从窗口系统接收鼠标,键盘和其他事件,并在屏幕上绘制自己。每个Widget 都是矩形的,它们按照Z-order 进行排序。注:Z-order是重叠二维对象的顺序,例如堆叠窗口管理器中的窗口。典型的GUI 的特征之一是窗口可能重叠,使得一个窗口隐藏另一个窗口的一部分或全部。当两个窗口重叠时,它们的Z 顺序确定哪个窗口出现在另一个窗口的顶部。理解:术语"z-order"指沿着z 轴物体的顺序。三维坐标轴中x横轴,y 数轴,z 上下轴。可以将gui 窗口视为平行与显示平面的一系列平面。因此,窗口沿着z 轴堆叠。所以z-order 指定了窗口的前后顺序。就像您桌面上的一叠纸一样,每张纸是一个窗口,桌面是您的屏幕,最上面的窗口z 值最高。QWidget 不是一个抽象类,它可以用作其他Widget的容器,并很容易作为子类来创建定制Widget。它经常用于创建、放置和容纳其他的Widget窗口。由上可知,QWidget 一般用于容纳其他Widget 窗口,其属性和方法相当的多,对于初学
者,我们通常只用它来作可以容纳其他窗口的容器,还会用来接收鼠标,键盘和其他事件等。
QMdiArea 继承QAbstractScrollArea。QMdiArea 小部件提供一个显示MDI 窗口的区域。
QMdiArea 的功能本质上类似于MDI 窗口的窗口管理器。大多数复杂的程序,都使用MDI 框架,在Qt designer 中可以直接将控件MDI Area 拖入使用。
QDockWidget inherits QWidget. The QDockWidget class provides a widget that can be docked within a QMainWindow or floated as a top-level window on the desktop. QDockWidget provides the concept of a docked widget, also known as a tool panel or utility window. A dock window is a secondary window placed in the dock widget area near the central window of QMainWindow. Dock windows can be moved within the current region, moved to a new region, and floated (ie, undocked
) by the end user. The QDockWidget API allows programmers to limit the ability of dock widgets to move, float, and close, as well as the area in which they can be placed. The initial docking areas of QDockWidget are Qt.BottomDockWidgetArea (bottom docking), Qt.LeftDockWidgetArea (left docking), Qt.RightDockWidgetArea (right docking), Qt.TopDockWidgetArea (top docking) and Qt.NoDockWidgetArea (Widget is not displayed). In the front some
small The controls in this section have already been used in this section, such as the QWidget widget. The controls listed above will be further explained and used below.

QGroupBox

7.7.1.1 Control Introduction
The QGroupBox widget provides a group box frame with a title. Generally used with a group or components of the same type.

Usage example
Example 33_qgroupbox, group box example (difficulty: easy), uses 3 QRadioButton radio button buttons, and QVBoxLayout (vertical layout) to show the basic use of the group box.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 #ifndef MAINWINDOW_H
2 #define MAINWINDOW_H
3
4 #include <QMainWindow>
5 #include <QRadioButton>
6 #include <QGroupBox>
7 #include <QVBoxLayout>
8
9 class MainWindow : public QMainWindow
10 {
    
    
11 Q_OBJECT
12
13 public:
14 MainWindow(QWidget *parent = nullptr);
15 ~MainWindow();
16
17 private:
18 /* 声明对象*/
19 QGroupBox *groupBox;
20 QVBoxLayout *vBoxLayout;
21 QRadioButton *radioButton[3];
22 };
23 #endif // MAINWINDOW_

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QList >
3
4 MainWindow::MainWindow( QWidget *parent )
5 : QMainWindow( parent )
	6
{
    
    
	7               /* 设置主窗体位置与大小*/
	8 this->setGeometry( 0, 0, 800, 480 );
	9               /* 以标题为“QGroupBox 示例”实例化groupBox对象*/
	10 groupBox = new QGroupBox( tr( "QGroupBox示例" ), this );
	11 groupBox->setGeometry( 300, 100, 300, 200 );
	12
	13 vBoxLayout = new QVBoxLayout();
	14
	15              /* 字符串链表*/
	16 QList <QString>list;
	17 list << "选项一" << "选项二" << "选项三";
	18 for ( int i = 0; i < 3; i++ )
	{
    
    
		19 radioButton[i] = new QRadioButton();
		20 radioButton[i]->setText( list[i] );
		21      /* 在vBoxLayout添加radioButton */
		22 vBoxLayout->addWidget( radioButton[i] );
		23
	}
	24              /* 添加一个伸缩量1 */
	25 vBoxLayout->addStretch( 1 );
	26              /* vBoxLayout布局设置为groupBox布局*/
	27 groupBox->setLayout( vBoxLayout );
	28
}


29
30 MainWindow::~MainWindow()
31
{
    
    
	32
}



在源文件“main.cpp”具体代码如下。由新建项目时生成,无改动。

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
}



运行效果
程序编译运行的结果如下,可以看到radioButton 有规则的排布在groupBox 组框里面。
Insert image description here

QScrollArea

7.7.2.1 控件简介
QScrollArea 类提供到另一个小部件的滚动视图。
7.7.2.2 用法示例
例34_qscrollarea 滚动视图(难度:简单),使用一个Label 标签,将Label 标签设置为一张图片,并把Label 标签放置于滚动区域内,此时图片应要大于滚动区域才会出现滚动条。
在新建例程中不要勾选“Generate form”,默认继承QMainWindow 类即可。项目新建完成,并添加了一张资源图片(添加资源图片的步骤请参考7.1.4 小节),如下图。
Insert image description here
在头文件“mainwindow.h”具体代码如下。

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QScrollArea >
6 # include < QLabel >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 定义QScrollArea对象*/
	18 QScrollArea * scrollArea;
	19 QLabel * label;
	20
};
21 # endif      /* MAINWINDOW_H */

在源文件“mainwindow.cpp”具体代码如下。

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6 this->setGeometry( 0, 0, 800, 480 );
	7
	8 scrollArea = new QScrollArea( this );
	9       /* 设置滚动区域为700*380 */
	10 scrollArea->setGeometry( 50, 50, 700, 380 );
	11
	12 label = new QLabel();
	13      /* label显示的lantingxu.png图片分辨率为1076*500 */
	14 QImage image( ":/images/lantingxu.png" );
	15 label->setPixmap( QPixmap::fromImage( image ) );
	16
	17 scrollArea->setWidget( label );
	18
	19
}


20
21 MainWindow::~MainWindow()
22
{
    
    
	23
}



在源文件“main.cpp”具体代码如下。由新建项目时生成,无改动。

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
}



运行效果
程序编译运行的结果如下,由于图片的大小大于滚动区域的大小,所以在滚动区域出现了滚动条,可以拖动滚动条来查看这张图片其余部分。
Insert image description here

QToolBox

7.7.3.1 Introduction to Controls
QToolBox (toolbox class) provides a column-like stacked window, translated into Chinese as toolbox, similar to a drawer.
7.7.3.2 Usage examples
Example 35_qtoolbox, QToolBox of QQ friend panel (difficulty: easy), this example will use the previous knowledge QGroupBox group box and QBoxLayout layout management. We have already learned the QGroupBox group box and QBoxLayout before. With the previous foundation, it will be much faster to understand this example.
The idea of ​​this example: use 6 QToolButtons to be divided into 2 groups, use vertical layout to arrange the 2 groups of QToolButtons, then add them to 2 groups of QGroupBox group boxes, and then add 2 groups of QGroupBox group boxes to the QToolBox as children.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The project is newly created, and several resource images have been added (please refer to Section 7.1.4 for the steps of adding resource images), as shown in the figure below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QToolBox >
6 # include < QGroupBox >
7 # include < QToolButton >
8 # include < QVBoxLayout >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19 /* 声明对象*/
	20 QToolBox * toolBox;
	21 QGroupBox * groupBox[2];
	22 QVBoxLayout * vBoxLayout[2];
	23 QToolButton * toolButton[6];
	24
	25
};
26 # endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6 this->setGeometry( 0, 0, 800, 480 );
	7
	8 toolBox = new QToolBox( this );
	9 toolBox->setGeometry( 300, 50, 200, 250 );
	10 /* 设置toolBox的样式,此处设置为30%不透明度的黑色*/
	11 toolBox->setStyleSheet( "QToolBox {
    
    background-color:rgba(0, 0, 0,
30%);}" );
	12
	13 for ( int i = 0; i < 2; i++ )
	{
    
    
		14 vBoxLayout[i]	= new QVBoxLayout();
		15 groupBox[i]		= new QGroupBox( this );
		16
	}
	17
	18      /* 字符串链表*/
	19 QList <QString>strList;
	20 strList << "李白" << "王照君" << "李元芳" << "程咬金" << "钟馗" << "上官婉儿";
	21
	22      /* 字符串图标链表*/
	23 QList <QString>iconsList;
	24 iconsList << ":/icons/libai" << ":/icons/wangzhaojun"
	25 << ":/icons/liyuanfang" << ":/icons/chengyaojin"
	26 << ":/icons/zhongkui" << ":/icons/shangguanwaner";
	27
	28 for ( int i = 0; i < 6; i++ )
	{
    
    
		29 toolButton[i] = new QToolButton();
		30              /* 设置toolButton图标*/
		31 toolButton[i]->setIcon( QIcon( iconsList[i] ) );
		32              /* 设置toolButton的文本*/
		33 toolButton[i]->setText( strList[i] );
		34              /* 设置toolButton的大小*/
		35 toolButton[i]->setFixedSize( 150, 40 );
		36              /* 设置toolButton的setToolButtonStyle的样式*/
		37 toolButton[i]->setToolButtonStyle(
			38 Qt::ToolButtonTextBesideIcon
			39 );
		40 if ( i < 3 )
		{
    
    
			41      /* 将toolButton添加到时垂直布局*/
			42 vBoxLayout[0]->addWidget( toolButton[i] );
			43      /* 添加一个伸缩量1 */
			44 vBoxLayout[0]->addStretch( 1 );
			45
		} else {
    
    
			46 vBoxLayout[1]->addWidget( toolButton[i] );
			47 vBoxLayout[1]->addStretch( 1 );
			48
		}
		49
	}
	50      /* 将垂直布局的内容添加到组框groupBox */
	51 groupBox[0]->setLayout( vBoxLayout[0] );
	52 groupBox[1]->setLayout( vBoxLayout[1] );
	53
	54      /* 将组框加入QToolBox里*/
	55 toolBox->addItem( groupBox[0], "我的好友" );
	56 toolBox->addItem( groupBox[1], "黑名单" );
	57
}


58
59 MainWindow::~MainWindow()
60
{
    
    
	61
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. This time, QToolButool is used as a sub-item of QGroupBox. Other QWidget widgets, such as QWidget, can also be used. (Note that the running effect of this program on Linux is as follows. If it is run on Windows, the display style of QToolBox may be different). Click on the "My Friends" list and a friend list will appear. Click on "Blacklist" and a blacklist list will appear.
Insert image description here

QTabWidget

7.7.4.1 Control Introduction
QTabWidget Inherits QWidget, and the QTabWidget class provides a set of tab (multi-page) widgets. QTabWidget is mainly used for paging display. Each page has one interface. Many interfaces share a common area, which saves the interface size and conveniently displays more information for users. It is similar to a browser's multi-tab page, so this control is often used in actual projects.
7.7.4.2 Usage examples
Example 36_qtabwidget, title bar multi-page switching (difficulty: easy), this example creates 3 pages, each page has a Label label component, clicking the tab of each page will switch to a different page superior.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The project is newly created and several resource pictures have been added (please refer to Section 7.1.4 for the steps of adding resource pictures), as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QTableWidget >
6 # include < QHBoxLayout >
7 # include < QLabel >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* 声明对象*/
	19 QWidget * widget;
	20 QTabWidget * tabWidget;
	21 QHBoxLayout * hBoxLayout;
	22 QLabel * label[3];
	23
};
24 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6 this->setGeometry( 0, 0, 800, 480 );
	7
	8 widget = new QWidget( this );
	9       /* 居中*/
	10 this->setCentralWidget( widget );
	11
	12      /* 多页面小部件*/
	13 tabWidget = new QTabWidget();
	14
	15      /* 水平布局实例化*/
	16 hBoxLayout = new QHBoxLayout();
	17 QList <QString>strLabelList;
	18 strLabelList << "标签一" << "标签二" << "标签三";
	19
	20 QList <QString>strTabList;
	21 strTabList << "页面一" << "页面二" << "页面三";
	22
	23 QList <QString>iconList;
	24 iconList << ":/icons/icon1"
	25 << ":/icons/icon2"
	26 << ":/icons/icon3";
	27
	28 for ( int i = 0; i < 3; i++ )
	{
    
    
		29 label[i] = new QLabel();
		30      /* 设置标签文本*/
		31 label[i]->setText( strLabelList[i] );
		32      /* 标签对齐方式(居中)*/
		33 label[i]->setAlignment( Qt::AlignCenter );
		34      /* 添加页面*/
		35 tabWidget->addTab( label[i],
				      36 QIcon( iconList[i] ),
				      37 strTabList[i]
				      38 );
		39
	}
	40              /* 是否添加关闭按钮*/
	41              /* tabWidget->setTabsClosable(true); */
	42              /* 将tabWidget水平直排布*/
	43 hBoxLayout->addWidget( tabWidget );
	44              /* 将垂直布局设置到widget */
	45 widget->setLayout( hBoxLayout );
	46
}


47
48 MainWindow::~MainWindow()
49
{
    
    
	50
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. Clicking on the tabs of different pages will switch to different pages. This example can also be extended to use the void setTabsClosable(bool closeable) function to add a close button after the tab, and then connect the signal slot to close the page. There is no need to add code in this example, it is relatively simple.
Insert image description here

QStackedWidget

7.7.5.1 Control introduction
QStackedWidget inherits QFrame. The QStackedWidget class provides a stack of widgets where only one widget can be seen at a time, similar to QQ's settings panel.
QStackedWidget can be used to create user interfaces similar to those provided by QTabWidget. It is a convenience layout widget built on top of the QStackedLayout class. Often used with QListWidget, the effect is as shown in the figure below, the left is the QListWidget list, and the right is QStackedWidget. They are generally connected to signal slots. By clicking on the QListWidget list on the left and using the signal slot to connect, the QStackedWidget on the right can display different content, one widget at a time.
Insert image description here
Usage examples
Example 37_qstackedwidget, multi-page switching in the list bar (difficulty: easy), this example creates 3 stack pages, each page has a Label label component, clicking on different items in each list will switch to different pages.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QStackedWidget >
6 # include < QHBoxLayout >
7 # include < QListWidget >
8 # include < QLabel >
9
10 class MainWindow : public QMainWindow
	11 {
    
    
	12 Q_OBJECT
	13
	14 public:
	15 MainWindow( QWidget *parent = nullptr );
	16 ~MainWindow();
	17
	18 private:
	19      /* widget小部件*/
	20 QWidget * widget;
	21      /* 水平布局*/
	22 QHBoxLayout * hBoxLayout;
	23      /* 列表视图*/
	24 QListWidget * listWidget;
	25      /* 堆栈窗口部件*/
	26 QStackedWidget * stackedWidget;
	27      /* 3个标签*/
	28 QLabel * label[3];
	29
	30
};
31 # endif      /* MAINWINDOW_H */
32

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6 this->setGeometry( 0, 0, 800, 480 );
	7
	8       /* widget小部件实例化*/
	9 widget = new QWidget( this );
	10
	11      /* 设置居中*/
	12 this->setCentralWidget( widget );
	13
	14      /* 垂直布局实例化*/
	15 hBoxLayout = new QHBoxLayout();
	16
	17      /* 堆栈部件实例化*/
	18 stackedWidget = new QStackedWidget();
	19
	20      /* 列表实例化*/
	21 listWidget = new QListWidget();
	22
	23 QList <QString>strListWidgetList;
	24 strListWidgetList << "窗口一" << "窗口二" << "窗口三";
	25
	26 for ( int i = 0; i < 3; i++ )
	{
    
    
		27 /* listWidget插入项*/
		28 listWidget->insertItem(
			29 i,
			30 strListWidgetList[i]
			31 );
		32
	}
	33
	34 QList <QString>strLabelList;
	35 strLabelList << "标签一" << "标签二" << "标签三";
	36
	37 for ( int i = 0; i < 3; i++ )
	{
    
    
		38 label[i] = new QLabel();
		39      /* 设置标签文本*/
		40 label[i]->setText( strLabelList[i] );
		41      /* 标签对齐方式(居中)*/
		42 label[i]->setAlignment( Qt::AlignCenter );
		43      /* 添加页面*/
		44 stackedWidget->addWidget( label[i] );
		45
	}
	46
	47              /* 设置列表的最大宽度*/
	48 listWidget->setMaximumWidth( 200 );
	49              /* 添加到水平布局*/
	50 hBoxLayout->addWidget( listWidget );
	51 hBoxLayout->addWidget( stackedWidget );
	52
	53              /* 将widget的布局设置成hboxLayout */
	54 widget->setLayout( hBoxLayout );
	55
	56              /* 利用listWidget的信号函数currentRowChanged()与
	                 * 57 * 槽函数setCurrentIndex(),进行信号与槽连接
	                 * 58 */
	59 connect( listWidget, SIGNAL( currentRowChanged( int ) ),
		    60 stackedWidget, SLOT( setCurrentIndex( int ) ) );
	61
}


62
63 MainWindow::~MainWindow()
64
{
    
    
	65
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. Clicking on different items in the list view will switch to different pages.
Insert image description here

QFrame

Examples have been given in Section 7.3.5.

QWidget

7.7.7.1 Control Introduction
QWidget class is the base class of all user interface objects (for example, QLabel class inherits from QFrame class, and QFrame class inherits from QWidget class). A widget is the basic unit of user interface: it receives mouse, keyboard, and other events from the window system and draws itself on the screen. Each Widget is rectangular, and they are sorted according to Z-order.
Note: Z-order is the order of overlapping 2D objects, such as windows in a stacked window manager. One of the characteristics of a typical GUI is that windows may overlap, causing one window to hide part or all of another window. When two windows overlap, their Z order determines which window appears on top of the other.
Understanding: The term "z-order" refers to the order of objects along the z-axis. The three-dimensional coordinate axes are the x horizontal axis, the y numerical axis, and the z upper and lower axis. You can think of a GUI window as a series of planes parallel to the display plane. Therefore, the windows are stacked along the z-axis. So z-order specifies the front and back order of the windows. Just like a stack of paper on your desktop, each paper is a window, the desktop is your screen, and the topmost window has the highest z-value.
QWidget is not an abstract class; it can be used as a container for other Widgets and can be easily subclassed to create custom Widgets. It is often used to create, place and contain other Widget windows.
QWidget is used in many of the above examples, such as section 7.5.1. Please refer to it yourself. There are no specific examples to write, so it is relatively simple.

QMdiArea

7.7.8.1 Control introduction
QMdiArea inherits QAbstractScrollArea. The QMdiArea widget provides an area for displaying MDI windows.
QMdiArea functions essentially like a window manager for MDI windows. Most complex programs use the MDI framework, and the control MDI Area can be directly dragged into Qt designer for use.
7.7.8.2 Usage examples
Example 38_qmdiarea, parent-child window (difficulty: easy), this example creates an MDI Area and uses a button. Each time the button is clicked, a new MdiSubWindow window will be created in the MDI Area.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QMdiSubWindow >
6 # include < QMdiArea >
7 # include < QPushButton >
8
9 class MainWindow : public QMainWindow
	10 {
    
    
	11 Q_OBJECT
	12
	13 public:
	14 MainWindow( QWidget *parent = nullptr );
	15 ~MainWindow();
	16
	17 private:
	18      /* Mdi Area区域对象*/
	19 QMdiArea * mdiArea;
	20      /* MdiSubWindow子窗口对象*/
	21 QMdiSubWindow * newMdiSubWindow;
	22      /* 用作点击创建新的窗口*/
	23 QPushButton * pushButton;
	24
	25 private slots:
	26      /* 按钮槽函数*/
	27 void creat_newMdiSubWindow();


	28
	29
};
30 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置窗口的显示位置与大小*/
7 this->setGeometry(0, 0, 800, 480);
8 pushButton = new QPushButton("新建窗口", this);
9 pushButton->setGeometry(0, 30, 100, 30);
10
11 mdiArea = new QMdiArea(this);
12 /* 设置MDI Area区域大小*/
13 mdiArea->setGeometry(100, 30, 700, 430);
14 /* 连接信号槽*/
15 connect(pushButton, SIGNAL(clicked()),
16 this, SLOT(creat_newMdiSubWindow()));
17 }
18
19 void MainWindow::creat_newMdiSubWindow()
20 {
    
    
21 newMdiSubWindow = new QMdiSubWindow();
22 newMdiSubWindow->setWindowTitle("新建窗口");
23
24 /* 如果窗口设置了Qt::WA_DeleteOnClose 这个属性,
25 * 在窗口接受了关闭事件后,Qt会释放这个窗口所占用的资源
26 */
27 newMdiSubWindow->setAttribute(Qt::WA_DeleteOnClose);
28
29 /* 添加子窗口*/
30 mdiArea->addSubWindow(newMdiSubWindow);
31 /* 显示窗口,不设置时为不显示*/
32 newMdiSubWindow->show();
33 /* 自适应窗口*/
34 newMdiSubWindow->sizePolicy();
35 /* 以级联的方式排列所有窗口*/
36 // mdiArea->cascadeSubWindows();
37 /* 以平铺方式排列所有窗口*/
38 mdiArea->tileSubWindows();
39 }
40
41 MainWindow::~MainWindow()
42 {
    
    
43 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. When the New Window button is clicked, a new window titled "New Window" is created in the MDI Area. The figure below shows the effect of clicking the New Window multiple times. This example uses a button to create a new window. Readers can add other functions such as adding and deleting buttons. The content in the new window of this article is empty. NewMdiSubWindow can use the setWidget(QWidget *widget) method to add content, such as adding the QLineEdit we learned earlier.
Insert image description here

QDockWidget

7.7.9.1 控件简介
QDockWidget 继承QWidget。QDockWidget 类提供了一个小部件,可以停靠在QMainWindow内,也可以作为桌面的顶级窗口浮动。
QDockWidget 提供了停靠部件的概念,也称为工具面板或实用程序窗口。停靠窗口是放置在QMainWindow 中央窗口附近的停靠窗口部件区域中的辅助窗口。停靠窗口可以被移动到当前区域内,移动到新的区域,并由终端用户浮动(例如,不停靠)。QDockWidget API 允许程序员限制dock widget 的移动、浮动和关闭能力,以及它们可以放置的区域。QDockWidget 的初始停
靠区域有Qt.BottomDockWidgetArea(底部停靠)、Qt.LeftDockWidgetArea(左边停靠、;Qt.RightDockWidgetArea (右边停靠)、Qt.TopDockWidgetArea (顶部停靠)和Qt.NoDockWidgetArea(不显示Widget)。
7.7.9.2 用法示例
例39_qdockwidget,停靠窗口(难度:简单),本例创建一个停靠窗口,在停靠窗口里添加文本编辑框,并且把这个停靠窗口放置到QMainWindow 的顶部。
在新建例程中不要勾选“Generate form”,默认继承QMainWindow 类即可。项目新建完成,如下图。
Insert image description here
在头文件“mainwindow.h”具体代码如下。

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QDockWidget >
6 # include < QTextEdit >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* 停靠窗口部件*/
	18 QDockWidget * dockWidget;
	19      /* 文本编辑框*/
	20 QTextEdit * textEdit;
	21
	22
};
23 # endif      /* MAINWINDOW_H */

在源文件“mainwindow.cpp”具体代码如下。

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置主窗体的显示的位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9       /* 实例化标题为停靠窗口*/
	10 dockWidget = new QDockWidget( "停靠窗口", this );
	11
	12      /* 实例化文本编辑框*/
	13 textEdit = new QTextEdit( dockWidget );
	14
	15 textEdit->setText( "这是一个测试" );
	16
	17      /* 停靠窗口添加文本编辑框*/
	18 dockWidget->setWidget( textEdit );
	19
	20      /* 放在主窗体的顶部*/
	21 this->addDockWidget( Qt::TopDockWidgetArea, dockWidget );
	22
}


23
24 MainWindow::~MainWindow()
25
{
    
    
	26
}



在源文件“main.cpp”具体代码如下。由新建项目时生成,无改动。

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
}



运行效果
程序编译运行的结果如下。拖动停靠窗口可以移动到另一个位置,松手则停靠。
Insert image description here

项目视图组(基于模型)

Insert image description here
What needs to be noted in the above figure is that in lower versions of Qt, Column View and Undo View are not encapsulated into visual controls
in Qt Creator.
The explanations of each of the above controls are as follows:
(1) List View: List view
(2) Tree View: Tree view
(3) Table View: Table view
(4) Column View: List view
(5) Undo View: Undo the
following list view Here is an introduction to each control:
QListView inherits QAbstractItemView, which is inherited by QListWidget and QUndoView. The QListView class provides a list or icon view on a model. QListView displays items stored in the model as a simple non-hierarchical list or collection of icons. This class is used to provide the list and icon views previously provided by the QListBox and QIconView classes, but using the more flexible approach provided by Qt's model/view architecture. QListView is based on Model, while QListWidget is based on Item. This is their essential difference. QListView requires modeling, so redundant data is reduced and the program is efficient; QListWidget is an upgraded version of QListView (essentially a QListView that encapsulates the model). It has already established a data storage model (QListWidgetItem) for us. , easy to operate, just call addItem to add items (ICON, text).
QTreeView inherits QAbstractItemView, which is inherited by QTreeWidget. The QTreeView class provides the default model/view implementation of tree views. QTreeView implements a tree representation of model items. This class is used to provide the standard hierarchical list previously provided by the QListView class, but using a more flexible approach provided by Qt's model/view architecture.
QTableView inherits QAbstractItemView, which is inherited by QTableWidget. The QTableView class provides a default model/view implementation of table views. QTableView implements a table view for displaying items from a model. This class is used to provide the standard tables formerly provided by the QTable class, but using the more flexible approach provided by Qt's model/view architecture.
QColumnView inherits QAbstractItemView. QColumnView displays a model within many QListViews, one for each hierarchy in the tree. This is sometimes called a cascading list. The QColumnView class is one of the model/view classes and is part of the Qt model/view framework. QColumnView implements the interface defined by the QAbstractItemView class to allow it to display data provided by a model derived from the QAbstractItemModel class.
QUndoView inherits QlistView. The QUndoView class displays the contents of the QUndoStack. QUndoView is a QListView that displays a list of commands pushed on the undo stack. Always select the most recently executed command. Selecting a different command causes QUndoStack::setIndex() to be called, scrolling the document's state backward or forward to the new command. The stack can be set explicitly using setStack(). Alternatively, you can use setGroup() to set the QUndoGroup object. The view will automatically update itself when the group's activity stack changes.

QListView

7.8.1.1 Control introduction
QListView inherits QAbstractItemView and is inherited by QListWidget and QUndoView. The QListView class provides a list or icon view on a model. QListView displays items stored in the model as a simple non-hierarchical list or collection of icons. This class is used to provide list and icon views previously provided by the QListBox and QIconView classes, but using the more flexible approach provided by Qt's model/view architecture. QListView is based on Model, while QListWidget is based on Item. This is their essential difference. QListView needs to be modeled, so redundant data is reduced, and the program efficiency is high;
while QListWidget is an upgraded version of QListView (essentially QListView that encapsulates the model), it has established a data storage model for us (QListWidgetItem) , easy to operate, just call addItem to add items (ICON, text).
QT provides some ready-made models for processing data items (these are the essence of Qt processing data model, if Qt data model is used, the following are often used): (1) QStringListModel is used to store simple QString
list .
(2) QStandardItemModel manages complex tree structure data items, each item can contain arbitrary data.
(3) QDirModel provides file and directory information in the local file system.
(4) QSqlQueryModel, QSqlTableModel, QSqlRelationTableModel are used to access the database.
7.8.1.2 Usage examples
Example 40_qlistview, list view (difficulty: easy). Use a ListView control to show how to insert data into a list, where the contents of the table can be edited and deleted.
Do not check "Generate form" in the new routine, and inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QListView >
6 # include < QStringListModel >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* QListView对象*/
	18 QListView * listView;
	19      /* 字符串模型对象*/
	20 QStringListModel * stringListModel;
	21
	22
};
23 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6       /* 设置主窗口位置与大小*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9       /* 实例化*/
	10 listView = new QListView( this );
	11      /* 将listView居中*/
	12 setCentralWidget( listView );
	13
	14 QStringList strList;
	15 strList << "高三(1)班" << "高三(2)班" << "高三(3)班";
	16
	17      /* 实例化,字符串模型*/
	18 stringListModel = new QStringListModel( strList );
	19
	20      /* 向表中插入一段数据*/
	21 listView->setModel( stringListModel );
	22      /* 设置为视图为图标模式*/
	23 listView->setViewMode( QListView::IconMode );
	24      /* 设置为不可拖动*/
	25 listView->setDragEnabled( false );
	26
}


27
28 MainWindow::~MainWindow()
29
{
    
    
	30
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. Double-click an item in the table to modify the content of the table, and you can also delete the content, etc.
Insert image description here

QTreeView

7.8.2.1 Control introduction
QTreeView inherits QAbstractItemView and is inherited by QTreeWidget. The QTreeView class provides the default model/view implementation of tree views. QTreeView implements a tree representation of model items. This class is used to provide the standard hierarchical list previously provided by the QListView class, but using a more flexible approach provided by Qt's model/view architecture.
Usage example 41_qtreeview, imitation word title (difficulty: easy). To enable a QTreeView to display data, you need to construct a model and set up the QTreeView. Qt provides some types of Models, the most commonly used of which is the QStandardItemModel class, which can generally meet most needs. In addition, the content of the header is also managed by this model. The setHorizontalHeaderLabels function can set the total number of columns and the text in each column.
The first-level title is directly added to the model using the appendRow method, and the secondary title is added to the first parent title, forming a parent-child relationship tree in turn.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The project is newly created, as shown in the figure below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

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

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 # include < QStandardItemModel >
4 # include < QStandardItem >
5
6 MainWindow::MainWindow( QWidget *parent )
7 : QMainWindow( parent )
	8
{
    
    
	9       /* 设置窗口的位置与大小*/
	10 this->setGeometry( 0, 0, 800, 480 );
	11      /* 实例化QTreeView对象*/
	12 treeView = new QTreeView( this );
	13      /* 居中*/
	14 setCentralWidget( treeView );
	15
	16      /* 构建Model */
	17 QStandardItemModel * sdiModel = new QStandardItemModel( treeView );
	18 sdiModel->setHorizontalHeaderLabels(
		19 QStringList() << QStringLiteral( "标题" )
		20 << QStringLiteral( "名称" )
		21 );
	22
	23 for ( int i = 0; i < 5; i++ )
	{
    
    
		24              /* 一级标题*/
		25 QList<QStandardItem*> items1;
		26 QStandardItem * item1 =
			27 new QStandardItem( QString::number( i ) );
		28 QStandardItem * item2 =
			29 new QStandardItem( QStringLiteral( "一级标题" ) );
		30              /* 添加项一*/
		31 items1.append( item1 );
		32              /* 添加项二*/
		33 items1.append( item2 );
		34              /* appendRow方法添加到model上*/
		35 sdiModel->appendRow( items1 );
		36
		37 for ( int j = 0; j < 5; j++ )
		{
    
    
			38      /* 在一级标题后面插入二级标题*/
			39 QList<QStandardItem*> items2;
			40 QStandardItem * item3 =
				41 new QStandardItem( QString::number( j ) );
			42 QStandardItem * item4 =
				43 new QStandardItem( QStringLiteral( "二级标题" ) );
			44 items2.append( item3 );
			45 items2.append( item4 );
			46      /* 使用appendRow方法添加到item1上*/
			47 item1->appendRow( items2 );
			48
		}
		49
	}
	50                      /* 设置Model给treeView */
	51 treeView->setModel( sdiModel );
	52
}


53
54 MainWindow::~MainWindow()
55
{
    
    
	56
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. You can click on the number to expand the secondary headings.
Insert image description here

QTableView

7.8.3.1 Control introduction
QTableView inherits QAbstractItemView and is inherited by QTableWidget. The QTableView class provides a default model/view implementation of table views. QTableView implements a table view for displaying items from a model. This class is used to provide the standard tables formerly provided by the QTable class, but using the more flexible approach provided by Qt's model/view architecture.
7.8.3.2 Example of usage
Example 42_qtableview, table view (difficulty: easy). To enable a QTableView to display data, a model needs to be constructed and set to the QTableView. Qt provides some types of Models, the most commonly used of which is the QStandardItemModel class, which can generally meet most needs. In addition, the content of the header is also managed by this model. The setHorizontalHeaderLabels function can set the total number of columns and the text in each column.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

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

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QStandardItemModel >
3 # include < QHeaderView >
4
5 MainWindow::MainWindow( QWidget *parent )
6 : QMainWindow( parent )
	7
{
    
    
	8       /* 设置窗口的位置与大小*/
	9 this->setGeometry( 0, 0, 800, 480 );
	10 tableView = new QTableView( this );
	11 setCentralWidget( tableView );
	12      /* 显示网格线*/
	13 tableView->setShowGrid( true );
	14
	15 QStandardItemModel * model	= new QStandardItemModel();
	16 QStringList labels		=
		17 QObject::tr( "语文,数学,英语" ).simplified().split( "," );
	18      /* 设置水平头标签*/
	19 model->setHorizontalHeaderLabels( labels );
	20
	21      /* item */
	22 QStandardItem * item = 0;
	23      /* model插入项内容*/
	24 for ( int i = 0; i < 5; i++ )
	{
    
    
		25 item = new QStandardItem( "80" );
		26 model->setItem( i, 0, item );
		27 item = new QStandardItem( "99" );
		28 model->setItem( i, 1, item );
		29 item = new QStandardItem( "100" );
		30 model->setItem( i, 2, item );
		31
	}
	32      /* 将model设置给tableView */
	33 tableView->setModel( model );
	34      /* 平均分列*/
	35 tableView->horizontalHeader()
	36->setSectionResizeMode( QHeaderView::Stretch );
	37      /* 平均分行*/
	38 tableView->verticalHeader()
	39->setSectionResizeMode( QHeaderView::Stretch );
	40
}


41
42 MainWindow::~MainWindow()
43 {
    
    
	44

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. A score table was created.
Insert image description here

QColumnView

7.8.4.1 Control introduction
QColumnView inherits QAbstractItemView. QColumnView displays a model within many QListViews, one for each hierarchy in the tree. This is sometimes called a cascading list. The QColumnView class is one of the model/view classes and is part of the Qt model/view framework. QColumnView implements the interface defined by the QAbstractItemView class to allow it to display data provided by a model derived from the QAbstractItemModel class.
Usage example
Example 43_qcolumnview, delivery address (difficulty: easy). Use a QColumnView and insert multi-level QStandardItems into it. This can simulate a multi-cascade view. It is very similar to the delivery address we filled in like a certain treasure and a certain east.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

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

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QStandardItem >
3
4 MainWindow::MainWindow( QWidget *parent )
5 : QMainWindow( parent )
	6
{
    
    
	7       /* 设置主窗体显示位置与大小*/
	8 this->setGeometry( 0, 0, 800, 480 );
	9 QStandardItemModel * model = new QStandardItemModel;
	10
	11      /* 省份*/
	12 QStandardItem * province = new QStandardItem( "广东省" );
	13
	14      /* 城市*/
	15 QStandardItem * city1	= new QStandardItem( "茂名市" );
	16 QStandardItem * city2	= new QStandardItem( "中山市" );
	17
	18      /* 添加城市到省份下*/
	19 province->appendRow( city1 );
	20 province->appendRow( city2 );
	21
	22 QStandardItem * town1	= new QStandardItem( "电白镇" );
	23 QStandardItem * town2	= new QStandardItem( "南头镇" );
	24
	25      /* 添加城镇到城市下*/
	26 city1->appendRow( town1 );
	27 city2->appendRow( town2 );
	28
	29 columnView = new QColumnView;
	30
	31      /* 建立model */
	32 model->appendRow( province );
	33
	34      /* 设置model */
	35 columnView->setModel( model );
	36
	37      /* 设置居中*/
	38 setCentralWidget( columnView );
	39
}


40
41 MainWindow::~MainWindow()
42
{
    
    
	43
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. When you click on a province, a city appears, and when you click on a city, a town appears.
Insert image description here

QUndoView

Control introduction
QUndoView inherits QlistView. The QUndoView class displays the contents of a QUndoStack. QUndoView is a QListView that displays a list of commands pushed on the undo stack. Always select the most recently executed command. Selecting a different command causes QUndoStack::setIndex() to be called, scrolling the document's state backward or forward to the new command. The stack can be set explicitly using setStack(). Alternatively, you can use setGroup() to set the QUndoGroup object.
The view automatically updates itself when the group's activity stack changes .
7.8.5.2 Usage examples
Example 44_qundoview, imitating PS history (difficulty: normal). If you have studied PS, you all know that there is a history panel in PS. Clicking it will revert to the history steps. For examples, you can also refer to the official example "UndoFramework Example" provided by Qt. However, the official examples are too complicated and it takes a lot of time to understand them. So the author wrote an example imitating PS history records to deepen everyone's understanding of QUndoView.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. Two new files were added at the same time. Click New, select C++> C++ Source File and name the command.h and command.cpp files for rewriting QUndoCommand. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "command.h" is as follows.

1 # ifndef COMMAND_H
2 # define COMMAND_H
3
4 # include < QUndoCommand >
5 # include < QObject >
6
7 class addCommand : public QUndoCommand
	8 {
    
    
	9 public:
	10 addCommand( int *value, QUndoCommand* parent = 0 );
	11 ~addCommand();
	12
	13 /* 重写重做与撤回方法*/
	14 void redo() override;


	15 void undo() override;


	16
	17 private:
	18      /* 新的count */
	19 int *new_count;
	20
	21      /* 旧的count */
	22 int old_count;
	23
};
24
25 # endif      /* COMMAND_H */

The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QUndoView >
6 # include < QUndoStack >
7 # include < QHBoxLayout >
8 # include < QVBoxLayout >
9 # include < QPushButton >
10 # include < QLabel >
11 # include < command.h >
12
13 class MainWindow : public QMainWindow
	14 {
    
    
	15 Q_OBJECT
	16
	17 public:
	18 MainWindow( QWidget *parent = nullptr );
	19 ~MainWindow();
	20
	21 private:
	22      /* 水平布局*/
	23 QHBoxLayout * hLayout;
	24      /* 水平布局*/
	25 QVBoxLayout * vLayout;
	26      /* 用于容纳hLayout布局*/
	27 QWidget * mainWidget;
	28      /* 容器作用QWidget,用于容纳标签与按钮*/
	29 QWidget * widget;
	30      /* 存放QUndoCommand命令的栈*/
	31 QUndoStack * undoStack;
	32      /* 历史记录面板*/
	33 QUndoView * undoView;
	34      /* 用于显示计算结果*/
	35 QLabel * label;
	36      /* 按钮*/
	37 QPushButton * pushButton;
	38      /* 计算结果*/
	39 int count;
	40
	41 private slots:
	42 void pushButtonClieked();


	43 void showCountValue( int );


	44
};
45 # endif /* MAINWINDOW_H */

The specific code in the source file "command.cpp" is as follows.

1 # include "command.h"
2 # include < QDebug >
3
4 addCommand::addCommand( int *value, QUndoCommand *parent )
5
{
    
    
	6       /* 使用Q_UNUSED,避免未使用的数据类型*/
	7 Q_UNUSED( parent );
	8
	9       /* undoView显示的操作信息*/
	10 setText( "进行了加1操作" );
	11
	12      /* value的地址赋值给new_count */
	13 new_count = value;
	14
	15      /* 让构造函数传过来的*new_count的值赋值给old_count */
	16 old_count = *new_count;
	17
}


18
19              /* 执行stack push时或者重做操作时会自动调用*/
20 void addCommand::redo()
21
{
    
    
	22      /* 重新赋值给new_count */
	23 * new_count = old_count;
	24
	25      /* 打印出*new_count的值*/
	26 qDebug() << "redo:" << *new_count << endl;
	27
}


28
29              /* 回撤操作时执行*/
30 void addCommand::undo()
31
{
    
    
	32      /* 回撤操作每次应减一*/
	33 (*new_count)--;
	34
	35      /* 打印出*new_count的值*/
	36 qDebug() << "undo:" << *new_count << endl;
	37
}


38
39 addCommand::~addCommand()
40
{
    
    
	41
	42
}



The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2 # include < QDebug >
3
4 MainWindow::MainWindow( QWidget *parent )
5 : QMainWindow( parent )
	6
{
    
    
	7       /* 设置主窗体显示的位置与大小*/
	8 this->setGeometry( 0, 0, 800, 480 );
	9
	10      /* 实例一个水平布局,用于左侧按钮区域与右侧历史记录面板*/
	11 hLayout = new QHBoxLayout();
	12
	13      /* 实例一个水平布局,用于左侧标签与按钮*/
	14 vLayout = new QVBoxLayout();
	15
	16      /* 主Widget, 因为MainWindow自带一个布局,
	         * 17 * 我们要新建一个Widget容纳新布局
	         * 18 */
	19 mainWidget = new QWidget();
	20
	21      /* 用于存放命令行栈*/
	22 undoStack = new QUndoStack( this );
	23
	24      /* 用于容纳左侧标签与按钮布局*/
	25 widget = new QWidget();
	26
	27      /* 历史记录面板实例化*/
	28 undoView = new QUndoView( undoStack );
	29
	30      /* 实例一个按钮,用于加一操作*/
	31 pushButton = new QPushButton();
	32
	33      /* 标签,用于显示计算结果*/
	34 label = new QLabel();
	35
	36      /* 设置widget的大小*/
	37 widget->setMinimumSize( 400, 480 );
	38
	39      /* 将两个widget添加到水平布局*/
	40 hLayout->addWidget( widget );
	41 hLayout->addWidget( undoView );
	42
	43      /* 初始化count的值*/
	44 count = 0;
	45
	46      /* 显示初始化计算结果*/
	47 label->setText( "计算结果:" + QString::number( count ) );
	48 label->setAlignment( Qt::AlignCenter );
	49
	50      /* 左侧布局*/
	51 vLayout->addWidget( label );
	52 vLayout->addWidget( pushButton );
	53
	54      /* 左侧布局控件的高度设置*/
	55 label->setMaximumHeight( this->height() / 5 );
	56 pushButton->setMaximumHeight( this->height() / 5 );
	57
	58      /* 按钮文件设置*/
	59 pushButton->setText( "加1" );
	60
	61      /* 设置widget的布局为vLayout */
	62 widget->setLayout( vLayout );
	63
	64      /* 将主窗体的布局设置为hLayout */
	65 mainWidget->setLayout( hLayout );
	66
	67      /* 设置mainWidget为主窗体的居中widget */
	68 this->setCentralWidget( mainWidget );
	69
	70      /* 信号槽连接,按钮点击,执行加一操作*/
	71 connect( pushButton, SIGNAL( clicked() ), this,
		    72 SLOT( pushButtonClieked() ) );
	73
	74      /* 信号槽连接,历史记录项index发生变化,显示count大小*/
	75 connect( undoStack, SIGNAL( indexChanged( int ) ),
		    76 this, SLOT( showCountValue( int ) ) );
	77
}


78
79              /* 入栈操作会自动调用addCommand的redo */
80 void MainWindow::pushButtonClieked()
81
{
    
    
	82      /* 变量值加一*/
	83 count++;
	84
	85      /* value指向count的地址*/
	86 int *value = &count;
	87
	88      /* 用重写的addCommand类实例化*/
	89 QUndoCommand * add = new addCommand( value );
	90
	91      /* 入栈*/
	92 undoStack->push( add );
	93
}


94
95 void MainWindow::showCountValue( int )
96
{
    
    
	97 /* 标签用于显示计算结果*/
	98 label->setText( "计算结果:" + QString::number( count ) );
	99
}


100
101 MainWindow::~MainWindow()
102
{
    
    
	103
	104
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. Click the "Add 1" button, and the calculation result will be increased by 1. Use the arrow keys or the mouse to select the history panel on the right to redo or undo the operation. At the same time, the application output window will print out the debug information, and the calculation result will also return to The calculation result at this step.
Summary of this example: Using the mathematical operation method of adding one, the use of QUndoView is simply explained. If you think of a good usage scenario for QUndoView, you can imitate this example and further optimize it or expand your knowledge.
Insert image description here

Item control group (item based)

Insert image description here
We have learned about view groups in the previous section, and now we will learn about control groups. Observe carefully that some controls in the view group have similar names to the controls in the control group. Take QListWidget as an example. QListWidget inherits QListView. QListView is model-based, while QListWidget is item-based. The two controls can be used as appropriate on different occasions! Generally, model-based ones are used to process big data. The controls in the view group and control group are often used when displaying data in Qt! Everyone should know how to use them.
The explanations of each of the above controls are as follows:
(1) List Widget: list control
(2) TreeWidget: tree control
(3) Table Widget: table control
The following is a brief introduction to each control:
QListWidget inherits QListView. The QListWidget class provides an item-based list widget. QListWidget is a convenience class that provides a list view similar to that provided by QListView, but provides a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. QListView is based on model. You need to model it yourself (such as establishing QStringListModel, QSqlTableModel, etc.) and save the data. This greatly reduces data redundancy and improves the efficiency of the program, but it requires us to have a certain understanding of data modeling, and QListWidget is an upgraded version of QListView. It has established a data storage model (QListWidgetItem) for us. It is easy to operate. You can add items (ICON, text) by directly calling addItem.
QTreeWidget inherits QTreeView. The QTreeWidget class provides a tree view using a predefined tree model.
The QTreeWidget class is a convenience class that provides a standard tree widget with a classic item-based interface similar to that used by the QListView class in qt3. This class is based on Qt's model/view architecture and uses the default model to hold items, each of which is a QTreeWidgetItem.
QTableWidget inherits QTableView. The QTableWidget class provides an item-based table view with a default model. Table widgets provide applications with standard table display facilities. Items in a QTableWidget are provided by QTableWidgetItem.

QListWidget

7.9.1.1 Control introduction
QListWidget inherits QListView. The QListWidget class provides an item-based list widget. QListWidget is a convenience class that provides a list view similar to that provided by QListView (covered in the next section), but provides a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.
7.9.1.2 Usage examples
Example 45_qlistwidget, add "song" (difficulty: easy). This example uses a QListWidget and a button. When the button is clicked, the system will be called to open the file window and filter the files with the mp3 suffix (this example uses the touch command to create 2 files with the mp3 suffix, which are not real songs. In the terminal The input command is touch 0.mp3 1.mp3. In this example, two files with the suffix mp3 have been created under the project). When the system file selection box is opened, these two mp3 files will be selected and added as items of QListWidget. to the QListWidget's window. (PS: We need to use this kind of operation when writing a music player - opening a song. In fact, this example is a code part for opening a song.) Do not
check "Generate form" in the new routine, just inherit the QMainWindow class by default . The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QListWidget >
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 private:
	17 /* 声明对象*/
	18 QListWidget * listWidget;
	19 QPushButton * pushButton;
	20
	21 private slots:
	22 void pushButtonClicked();


	23
	24
};
25 # endif /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 #include "mainwindow.h"
2 #include "QFileDialog"
3
4 MainWindow::MainWindow(QWidget *parent)
5 : QMainWindow(parent)
6 {
    
    
7 /* 设置主窗口的显示位置与大小*/
8 this->setGeometry(0, 0, 800, 480);
9
10 listWidget = new QListWidget(this);
11
12 /* 设置listWidget的大小*/
13 listWidget->setGeometry(0, 0, 480, 480);
14
15 listWidget->addItem("请单击右边的添加项添加内容");
16
17 pushButton = new QPushButton(this);
18
19 /* 设置pushButton的位置与大小*/
20 pushButton->setGeometry(540, 200, 200, 100);
21 pushButton->setText("添加项");
22
23 /* 信号与槽连接*/
24 connect(pushButton, SIGNAL(clicked()),
25 this, SLOT(pushButtonClicked()));
26 }
27
28 void MainWindow::pushButtonClicked()
29 {
    
    
30 /* 调用系统打开文件窗口,设置窗口标题为“打开文件”,过滤文件名*/
31 QString fileName = QFileDialog::getOpenFileName(
32 this,tr("添加项"),"",
33 tr("Files(*.mp3)")
34 );
35
36 /* 判断是否选中打开mp3文件*/
37 if (fileName != NULL)
38 /* 添加项到列表中*/
39 listWidget->addItem(fileName);
40 }
41
42 MainWindow::~MainWindow()
43 {
    
    
44 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running effect
The results of program compilation and running are as follows. When you click the Add Item button, a dialog box for the system to select a file will appear. When the system opens the file, it will filter the file with the suffix of mp3. Click the file with the suffix of mp3, double-click or select it and then click "Open" in the upper right corner to open the file. Added to the QListWidget list on the left. Readers can imitate this example, and can also add buttons to delete items, or delete all buttons, etc. The song list of Kugou music player is similar to this. Continue to learn how to play music, and combine this to make a music player.
Insert image description here
Insert image description here

QTreeWidget

7.9.2.1 Control introduction
QTreeWidget inherits QTreeView. The QTreeWidget class provides a tree view using a predefined tree model.
The QTreeWidget class is a convenience class that provides a standard tree widget with a classic item-based interface similar to that used by the QListView class in qt3. This class is based on Qt's model/view architecture and uses the default model to hold items, each of which is a QTreeWidgetItem.
7.9.2.2 Usage examples
Example 46_qtreewidget, group sending messages (difficulty: average), this example uses a TreeWidget to simulate a Fetion contact group, and "sends" messages in groups by selecting contacts in the group. In fact, it is not actually a Fetion that sends group messages. It just simulates the scenario of selecting contacts when Fetion sends group messages, and uses examples to familiarize yourself with the use of QTreeWidget. This example is slightly longer than the previous example, and the concepts of tree nodes and sub-nodes appear. The idea of ​​​​this example: When the top-level tree node is selected, all sub-nodes are selected; when the top-level tree node is deselected, all the original selected states of the sub-nodes will be cancelled; when the sub-nodes are not completely selected, the tree nodes are displayed It is half-selected.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QTreeWidget >
6 # include < QTreeWidgetItem >
7
8 class MainWindow : public QMainWindow
	9 {
    
    
	10 Q_OBJECT
	11
	12 public:
	13 MainWindow( QWidget *parent = nullptr );
	14 ~MainWindow();
	15
	16 private:
	17      /* QTreeWidget对象*/
	18 QTreeWidget * treeWidget;
	19      /* 顶层树节点*/
	20 QTreeWidgetItem * parentItem;
	21      /* 声明三个子节点*/
	22 QTreeWidgetItem * subItem[3];
	23
	24      /* 子节点处理函数*/
	25 void updateParentItem( QTreeWidgetItem* );


	26
	27 private slots:
	28      /* 槽函数*/
	29 void treeItemChanged( QTreeWidgetItem*, int );


	30
	31
};
32 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows

1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent)
4 : QMainWindow(parent)
5 {
    
    
6 /* 设置主窗体大小*/
7 this->setGeometry(0, 0, 800, 480);
8
9 /* 实例化*/
10 treeWidget = new QTreeWidget(this);
11
12 /* 居中*/
13 setCentralWidget(treeWidget);
14
15 /* 清空列表*/
16 treeWidget->clear();
17
18 /* 实例化顶层树节点*/
19 parentItem = new QTreeWidgetItem(treeWidget);
20 parentItem->setText(0, "同事");
21
22 parentItem->setFlags(
23 Qt::ItemIsUserCheckable
24 | Qt::ItemIsEnabled
25 | Qt::ItemIsSelectable
26 );
27 /* 树节点设置为未选中*/
28 parentItem->setCheckState(0, Qt::Unchecked);
29
30 /* 字符串链表*/
31 QList <QString> strList;
32 strList<<"关羽"<<"刘备"<<"张飞";
33
34 for (int i = 0; i < 3; i++){
    
    
35 /* 实例化子节点*/
36 subItem[i] = new QTreeWidgetItem(parentItem);
37 /* 设置子节点的文本,参数0代表第0列*/
38 subItem[i]->setText(0, strList[i]);
39 /* 设置子节点的属性为用户可选、项开启、项可选*/
40 subItem[i]->setFlags(
41 Qt::ItemIsUserCheckable
42 | Qt::ItemIsEnabled
43 | Qt::ItemIsSelectable
44 );
45 /* 设置子节点的状态为未选中*/
46 subItem[i]->setCheckState(0,Qt::Unchecked);
47 }
48 /* 信号槽连接*/
49 connect(treeWidget,SIGNAL(itemChanged(QTreeWidgetItem* , int)),
50 this, SLOT(treeItemChanged(QTreeWidgetItem* , int)));
51
52 }
53
54 /* 更新树节点函数*/
55 void MainWindow::updateParentItem(QTreeWidgetItem *item)
56 {
    
    
57 /* 获取子节点的父节点(树节点)*/
58 QTreeWidgetItem* parent = item->parent();
59 if(parent == NULL){
    
    
60 return;
61 }
62 /* 初始化选中的数目为0,下面根据selectCount来判断树节点的状态*/
63 int selectCount = 0;
64 /* 获取树节点的子节点总数*/
65 int childCount = parent->childCount();
66 /* 循环判断子节点的状态*/
67 for(int i = 0; i < childCount; i ++){
    
    
68 QTreeWidgetItem* childItem =parent->child(i);
69 /* 判断当前子节点的状是否为选中状态,如果是,则加一*/
70 if(childItem->checkState(0) == Qt::Checked) {
    
    
71 selectCount ++;
72 }
73 }
74 /* 根据selectCount来判断树节点的状态*/
75 /* 当选中的子节点小于或等于0时,则为设置树节点为未选中状态*/
76 if (selectCount <= 0) {
    
    
77 /* 设置树节点为未选中状态*/
78 parent->setCheckState(0, Qt::Unchecked);
79 /* 部分选中时,树节点为半选状态*/
80 } else if (selectCount > 0 && selectCount < childCount) {
    
    
81 /* 设置为半选状态*/
82 parent->setCheckState(0, Qt::PartiallyChecked);
83 /* 子节点全选时*/
84 } else if (selectCount == childCount){
    
    
85 /* 设置为树节点为选中状态*/
86 parent->setCheckState(0, Qt::Checked);
87 }
88 }
89
90 void MainWindow::treeItemChanged(QTreeWidgetItem *item, int)
91 {
    
    
92 /* 获取子节点总数*/
93 int count = item->childCount();
94
95 /* 若顶层树节点选中*/
96 if(Qt::Checked == item->checkState(0) ) {
    
    
97 /* 若选中的项是树节点,count会大于0,否则选中的项是子节点*/
98 if (count > 0) {
    
    
99 for (int i = 0; i < count; i++) {
    
    
100 /* 子节点全选*/
101 item->child(i)->setCheckState(0, Qt::Checked);
102 }
103 } else {
    
    
104 /* 子节点处理*/
105 updateParentItem(item);
106 }
107 /* 若顶层树节点取消选中时*/
108 } else if (Qt::Unchecked == item->checkState(0)) {
    
    
109 if (count > 0){
    
    
110 /* 若选中的项是树节点,count会大于0,否则选中的项是子节点*/
111 for (int i = 0; i < count; i++) {
    
    
112 /* 子节点全不选*/
113 item->child(i)->setCheckState(0, Qt::Unchecked);
114 }
115 } else {
    
    
116 /* 子节点处理*/
117 updateParentItem(item);
118 }
119 }
120 }
121
122 MainWindow::~MainWindow()
123 {
    
    
124 }

The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. The picture below shows the state when all are selected, just like the scenario where all contacts are selected when sending a group message. When the tree node colleagues are selected, all child nodes (Guan Yu, Liu Bei, Zhang Fei) will be selected; when the tree node colleagues are not selected, the status of the child nodes (Guan Yu, Liu Bei, Zhang Fei) will be unselected; , Liu Bei, Zhang Fei) are selected and not all are selected, the status of the tree node colleagues will be half-selected.
Insert image description here

QTableWidget

7.9.3.1 Control introduction
QTableWidget inherits QTableView. The QTableWidget class provides an item-based table view with a default model. Table widgets provide applications with standard table display facilities. Items in a QTableWidget are provided by QTableWidgetItem.
7.9.3.2 Usage example
Example 47_qtablewidget, TabelWidget table (difficulty: simple), this example uses a TableWidget, draws a table, and modifies the title of the item at the same time, you can directly edit the content of the item by double-clicking in the table, and you can also delete the item Contents etc.
Do not check "Generate form" in the new routine, just inherit the QMainWindow class by default. The new project is completed, as shown below.
Insert image description here
The specific code in the header file "mainwindow.h" is as follows.

1 # ifndef MAINWINDOW_H
2 # define MAINWINDOW_H
3
4 # include < QMainWindow >
5 # include < QTableWidget >
6
7 class MainWindow : public QMainWindow
	8 {
    
    
	9 Q_OBJECT
	10
	11 public:
	12 MainWindow( QWidget *parent = nullptr );
	13 ~MainWindow();
	14
	15 private:
	16      /* QTabelWidget表格*/
	17 QTableWidget * tableWidget;
	18
	19      /* QTabelWidgetItem表格数据(项)*/
	20 QTableWidgetItem * tableWidgetItem[4];
	21
	22
};
23 # endif      /* MAINWINDOW_H */

The specific code in the source file "mainwindow.cpp" is as follows.

1 # include "mainwindow.h"
2
3 MainWindow::MainWindow( QWidget *parent )
4 : QMainWindow( parent )
	5
{
    
    
	6               /* 设置主窗体的大小与位置*/
	7 this->setGeometry( 0, 0, 800, 480 );
	8
	9               /* 实例化*/
	10 tableWidget = new QTableWidget( this );
	11              /* 设置tableWidget表居中*/
	12 setCentralWidget( tableWidget );
	13              /* 设置列数*/
	14 tableWidget->setColumnCount( 2 );
	15              /* 设置行数*/
	16 tableWidget->setRowCount( 2 );
	17              /* 使用标签设置水平标题标签*/
	18 tableWidget->setHorizontalHeaderLabels(
		19 QStringList() << "姓名" << "性别"
		20 );
	21
	22              /* 字符串类型链表*/
	23 QList <QString> strList;
	24 strList << "小明" << "小红" << "男" << "女";
	25
	26 for ( int i = 0; i < 4; i++ )
	{
    
    
		27      /* 实例化*/
		28 tableWidgetItem[i] = new QTableWidgetItem( strList[i] );
		29      /* 设置文本居中对齐*/
		30 tableWidgetItem[i]->setTextAlignment( Qt::AlignCenter );
		31
	}
	32              /* 插入数据,表的index就是一个二维数组数据*/
	33 tableWidget->setItem( 0, 0, tableWidgetItem[0] );
	34 tableWidget->setItem( 1, 0, tableWidgetItem[1] );
	35 tableWidget->setItem( 0, 1, tableWidgetItem[2] );
	36 tableWidget->setItem( 1, 1, tableWidgetItem[3] );
	37
	38
}


39
40 MainWindow::~MainWindow()
41
{
    
    
	42
}



The specific code in the source file "main.cpp" is as follows. It is generated when creating a new project without any changes.

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
}



Running results
The results of program compilation and running are as follows. Double-click an item in the table to modify the content of the table, and you can also delete the content, etc.
Insert image description here

Guess you like

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