8. Qt imports resource files

The Qt resource system is a cross-platform resource mechanism that is used to store the resources needed when the program is running in binary form inside the executable file. If your program needs to load specific resources (icons, text translations, etc.), then place them in resource files and you no longer need to worry about losing these files. In other words, if you store resources as resource files, they will be compiled into the executable file.

1. Create resource files

Resource files can be easily created using Qt Creator. We can right-click on the project and select "Add New File..." and find "Qt Resource File" under the Qt category:

Click the "Select..." button to open the "New Qt Resource File" dialog box. Here we enter the name and path of the resource file:

Click Next, select the required version control system, and then select Finish. We can see the "Resource File" item in the file list on the left of Qt Creator, which is our newly created resource file:

There is "Add" in the editing area on the right. We first need to add a prefix. For example, we name the prefix /. Then select this prefix and continue to click Add Files to find the files we need to add. Here, we select all png files. When we are done, Qt Creator should look like this:

Finally, we compile it: Our resources are successfully imported.

Next, we can also add additional prefixes or additional files. It depends on your needs.

After we add it, we can find this file by using the path starting with:. For example, if our prefix is ​​/ and the file is butterfly.png, then we can use:/images/butterfly.png to find this file.

One problem caused by this is that if we want to change the file name in the future, such as changing butterfly.png to btf.png, then all paths using this name need to be modified. Therefore, a better way is to give this file an "alias" and use this alias to reference the file in the future. The specific method is to select this file and add alias information:

In this way, we can directly use:/images/btf to reference this resource without caring about the real file name of the image.


2. How to add resource files in code

In the code, we setIconset the ui icon through a function.

  • We can call it through the absolute position of the resource file
  • It can also be called based on the relative prefix + file name (alias) of the resource file (note: this method requires putting the resource file into the file of the Qt program)
	//ui->actionnew->setIcon(QIcon("F:/Study/Qt/Qt-学习/QT资料/day2资料/Doc/Image/Luffy.png"));

    //添加Qt资源文件 ": + 前缀名 + 文件名"
    ui->actionnew->setIcon(QIcon(":/Image/Luffy.png"));
    ui->actionopen->setIcon(QIcon(":/Image/LuffyQ.png"));

The final effect is shown in the figure:

3. Program resources of this document

The Qt project files corresponding to this document can be found below:

02_QtSource.zip

Guess you like

Origin blog.csdn.net/qq_63388834/article/details/135138629