Qt 6 bis, a commonly used GUI library that supports Chinese in C++: project structure, use of resource files

Qt 6 bis, a commonly used GUI library that supports Chinese in C++: project structure, use of resource files

The download, installation and simple use of the previous Qt 6 https://blog.csdn.net/cnds123/article/details/130730203 , this article introduces the structure of the Qt 6 project, the use and release of resource files.

Base

This part, if you don’t understand what it means when you are a beginner, don’t get entangled, just get a general understanding first, and after a period of study and practice, you will be able to understand it better when you look back (review).

Features of the qmake , CMake and Qbs build systems in Qt6

qmake

qmake is very simple to use, and for most projects, it will suffice. Using qmake is a good choice if your project only needs basic build functionality, such as compiling and linking source files, managing dependent libraries, and creating installers.

CMake

CMake is a cross-platform build tool that can generate many different project file types, such as Makefile, Visual Studio Solution, etc. CMake is a bit more complicated to use than qmake, but it is more flexible and has advantages when dealing with larger projects. If you plan to develop larger applications or libraries, using CMake and integrating it with other build tools may be a better choice.

Qbs

Qbs is Qt's next-generation build tool, which is based on QML and JavaScript and provides a modern, modular and easy-to-use build language. Qbs requires some learning costs compared to qmake and CMake, but it is well supported and integrated, and it compiles faster. If you want better integration with Qt Creator while gaining greater advantages in build speed and project size, using Qbs may be a better choice.

Qt creates resource files in the following two ways:

1. Use Qt Creator to create resource files

Right-click the project folder or folder in Qt Creator, select "Add New" -> "Qt" -> "Qt Resource File", and set the name and save location of the resource file in the pop-up dialog box. Then add the resource files you need, such as pictures, audio, etc., in the resource file editor.

2. Manually create the .qrc file

You can manually create a .qrc file, and then add the path of the resource file and its related information in the file. For novices, it is difficult to say more.

Both of these methods can be used to create resource files in Qt6. Using Qt Creator can create .qrc files more quickly and conveniently, while manually creating .qrc files can control the addition and management of resource files more finely.

An overview of the use of project resource files created by different project build systems (qmake , CMake and Qbs ) :

1.qmake project

Right-click the project folder or folder in Qt Creator, select "Add New" -> "Qt" -> "Qt Resource File", and set the name and save location of the resource file in the pop-up dialog box. Then add the resource files you need, such as pictures, audio, etc., in the resource file editor.

After adding the resource file, the following code is automatically added in the .pro project file:

RESOURCES += resources.qrc

Among them, resources.qrc is the name of the resource file you just created.

2. CMake project:

The method of creating resource files in a CMake project is similar to that in a qmake project. You can create a resource file and add it to the project. For example, you can create a file called res.qrc in the project directory, and then add the following code to CMakeLists.txt:

qt6_add_resources(QTRESOURCES res.qrc)

add_executable(project_name ${QTRESOURCES} ...)

Among them, ${QTRESOURCES} means to package the resources in the res.qrc file into the project. Note its location in the file:

# CMakeLists.txt

# At the beginning it should be cmake_minimum_required and project command

# ...

# Find the CMake module file containing Qt

find_package(Qt6 COMPONENTS Widgets REQUIRED)

# The command to add resource files, here take res.qrc as an example

qt6_add_resources(QTRESOURCES res.qrc)

# Set up the project file

set(PROJECT_SRC_FILES

    main.cpp

    # ... other source files...

)

# Compile and link the executable

add_executable(project_name

    ${PROJECT_SRC_FILES}

    ${QTRESOURCES} # Add resource files to the executable

)

target_link_libraries(project_name

    Qt6::Widgets

    # ... other dependent libraries...

)

3. Qbs project:

Creating resource files in a Qbs project is slightly different from projects for the other two build tools.

First, you need to add the following code snippet to your project file to create an AssetBundle file:

// project path

var projectPath = project.sourceDirectory

// resource path

var assetsPath = projectPath.append("assets")

// create AssetBundle file

var bundle = AssetBundle {

    name: "res.qrc"

    files: [

        // add resource file

        assetsPath.append("icons/search.png")

    ]

}

project.addAssetBundle(bundle)

In the above code, project.sourceDirectory refers to the directory where the project file is located, and the assets folder is the resource file storage directory we assume exists. Here we use AssetBundle to create a res.qrc binary file, which contains image resources under the path of /assets/icons/search.png, which will be packaged into the AssetBundle file.

Then where you need to use the resource file, you need to use the following code snippet to load it:

import qbs

// load method

var resourceContent = "";

var resourcePath = qbs.getResolvedFilePath("qrc:/res.qrc/path/to/resource");

if (file.exists(resourcePath))

    resourceContent = file.read(resourcePath);

In the above code, we use qbs.getResolvedFilePath to get the path similar to the file system path. Then use the file.read command to read its content, which is the image resource we used before.

In short, using Qt Creator to create resource files can easily manage and use resource files. For different project construction tools, the specific operations are slightly different, and related specifications and grammars need to be followed.

Create a Qt project first

Requirement: Enter the radius value, and after clicking the "Calculate" button, the circle area value will be displayed

Run Qt Creator, click the "Projects" button on the left side of the welcome interface

The corresponding files have been automatically loaded into the project file list, as shown below:

After the QT Creator wizard creates a project, it will automatically generate some source files and resource files.

Now, interface design can be done

Click the Forms section to expand, double-click the .ui file, here is mainwindow.ui

Drag the slider of the control container bar, find the Label label control in the Display Widgets container bar, drag three of these controls to the middle form; similarly, find the Line Edit edit box control in the Input Widgets container bar, drag this control to In the middle form, it is used to enter the radius value; find the Push Button button control in the Buttons container bar, drag this control to the middle form, and use it to submit the response to the click event.

Then you need to modify the properties of each control. The corresponding properties of the controls in the form appear on the right, and you can modify them as shown in the table below.

CLass

text

objectName

frameShape

frameShadow

QLabel

radius

radiusLabel

QLabel

area

areaLabel_1

QLabel

areaLabel_2

Panel

Sunken

QLineEdit

radiusLineEdit

QPishButton

calculate

counBtn

Modified situation:

Now, write the function code to calculate the circle area

Enter the radius value in the "Line Edit" edit box, and then click the "Calculate" button, and the corresponding circle area will be displayed in areaLabel_2.

The operation steps are as follows.

Press the right mouse button on the "Calculation" button, select the "Go to slot..." command in the pop-up drop-down menu, select the "clicked()" signal of QAbstractButton in the "Go to slot" dialog box, and click "OK ” button, as shown in the picture:

Enter the slot function on_countBtn_clicked() of the button click event in the MainWindow.cpp file, and add the following code to this function:

void MainWindow:: on_countBtn_clicked()
{
    bool ok;
    QString tempStr;
    QString valueStr = ui->radiusLineEdit->text();
    int valueInt = valueStr.toInt(&ok);
    double area = valueInt * valueInt * PI;				//计算圆面积
    ui->areaLabel_2->setText(tempStr.setNum(area));
}

Add the following statement at the beginning of the MainWindow.cpp file:

const static double PI = 3.1416;

See the picture below:

Now you can compile and run the program

Enter the radius value in the "Line Edit" text box, and click the "Calculate" button to display the circle area value:

Structure of projects created by QT Creator

Projects created by QT Creator usually have the following structure, see the figure below:

 ☆Project files/Configuration files for the build system:

Qmake is a .pro file (application name.pro)

CMake is the CMakeLists.txt file

Qbs are .qbs files (appname.qbs)

They are all a text file that contains the configuration information of the entire project, including the required library files and header files.

☆Source code files (.cpp, .h): These files contain the implementation code and header files of the program. In QT Creator, these files can be organized through the "Sources" and "Headers" folders in the project directory.

☆Interface design files (.ui): These files are used to describe the user interface of the application. In QT Creator, these files can be organized through the "Forms" folder in the project directory.

☆Resource file (.qrc): If it has been created, it will not appear because it has not been created, and it will be created later. These files are used to manage images, audio, text, and other data files in the application. In QT Creator, these files can be organized through the "Resources" folder in the project directory.

☆Compiled output files (.exe, .dll, .so): These files are the final executable or library files generated by the compiler. In QT Creator, these files can be organized through the "Builds" folder in the Projects directory.

Use of resource files

The Qt Resource System (Qt Resource System) is a system that stores pictures and data in binary files.

In GUI programs, it is inevitable to use various resources, such as pictures, audio and video resources, etc. With these resources, we can set ordinary buttons to have pictures, and some labels can also be displayed with pictures. Play animations, etc.

In order to use these resources conveniently, we need to use the resource files (.qrc files) in Qt.

Qt uses resource files (.qrc files) to package the resource files (such as pictures, fonts, audio, etc.) required by the application into a binary file for easy access by the application, avoiding the path caused by the separation of resource files and applications question. The benefit of this approach is that packaging the resource files into the application makes the application more self-contained and portable. Wherever you copy your app, you can be sure it has the resources it needs without downloading or copying them again. Note that if you need to update resource files in your application (such as adding new images or changing existing ones), you will need to recompile your application to include the new resource files.

Use Qt Creator to create a resource file (.qrc file), you can follow the steps below :

Create a new Qt project or open an existing Qt project in Qt Creator.

Right-click on the Projects name in the project tree and select "Add New".

In the "Add New" dialog box, select "Qt" > "Qt Resource File (Qt Resoorce File)" > "Select (Change)" button.

On the "Location" page of the "Qt Resource File (Qt Resoorce File)" dialog box, enter the name and path of the resource file, and click "Next";

Then add resource files in the "Summary Page (Summary)" dialog box. Click the "Finish" button to complete adding resource files.

See the picture below:

After adding the resource file, the following operations can be performed.

Create icons . Qt program window icons support multiple image formats, such as ICO, PNG, SVG, etc.

In Qt Creator, open the .qrc file to add resource files :

Open your project in Qt Creator.

Select your project folder in the Projects panel on the left and click Expand.

Find the .qrc file and right click on it.

Select "Open in Editor" from the pop-up menu.

Now, you can use "Add Prefix" and "Add Files" in the resource view, and follow the prompts to add the corresponding files or folders.

First click the Add Prefix button in the resource view, adding a prefix name can be modified (the prefix name is mainly to distinguish the functions of these resources, such as background music resource files, or pictures specially used for buttons, or pictures specially used for avatars, etc. ). I create a /Res here

Then click the Add Files button to add the required resource files. In order to facilitate management and avoid misoperation and subsequent modification, it is recommended that you create a subfolder in the project directory and manually copy the resource files into it. [Otherwise the following prompt will appear

There are several ways to add a form icon (icon), an icon for a button, and a picture for the form background.

The following is how to set the form icon

Here I am (the project directory ch01, the resource file directory ResFolder)

Use "Add Prefix" and "Add Files" in the resource view, first add the Qt.png image file as the form image to the .qrc file, the operation steps: In Qt Creator, on the left "Projects (project) " panel, select your project folder, click to expand, find the .qrc file and right-click it, and select "Open in Editor (open in the editor)" in the pop-up menu, so that you can put the resource file - Here is the Qt.png image file added to the .qrc file. See the picture below:

Then do one of the following:

Method 1. Set directly in Qt Designer: In the form property editor, select the icon file in the "windowIcon" property bar.

Method 2, you can also use the code to set

Tip: To use a resource file in an application, you can use the ":/" prefix to represent the resource file, such as: QPixmap(":/images/logo.png"), where ":/" represents the root directory, followed by " images/logo.png" indicates the path in the resource file.

Here I add the icon file to the application source file, and add the following code in main.cpp:

QGuiApplication::setWindowIcon(QIcon(":/Res/ResFolder/Qt.png"));//Add window icon

See the picture below:

Use one of the two methods above.

Now run and see, in Qt Creator, you can compile the program through the [build Project "project name" Ctrl+B] option in the "build" menu, and then run the program through the [run Ctrl+B] option.

After running, the visible icon has changed:

Set the form background image

Use "Add Prefix" and "Add Files" in the resource view to first add the BGImage.jpg image file as the background image of the form to the .qrc file,

See the picture below:

Then proceed as follows:

Set directly in Qt Designer: In the form property editor, specify the background image path in the "styleSheet" property bar. See the picture below:

Note that background-image needs to be added manually in the above picture: 

You can also use code to set the background image of the form, which is cumbersome and will not be introduced here.

Now run, the background of the form is changed:

Special Note : Add the image file to the .qrc file, and the file will be packaged into the application binary file. This means that, when the application is run, it does not need to look for it on disk. Qt6 can read image data directly from the application binary and use it to display images or perform other operations. Wherever you copy your app, you can be sure it has the resources it needs without downloading or copying them again.

Please note that if you need to update the resource files in your application (such as adding new images or changing existing ones), you need to recompile the application [In Qt Creator, you can click the "Build Project" button or use shortcut "Ctrl+B" to do this] to include the new resource file.

For more information about the Qt resource system, please refer to https://zhuanlan.zhihu.com/p/60457016

Even if the above small application is developed, the next article introduces the release of the project:

Qt 6, a commonly used GUI library that supports Chinese in C++: Project release https://blog.csdn.net/cnds123/article/details/130827966

Guess you like

Origin blog.csdn.net/cnds123/article/details/130741807