Qt add resource file

In order to facilitate cross-platform use, Qt provides a resource system. The resource system is used to store the resources required by the program in a binary form inside the executable file. That is to compile the resource file into a part of the executable file. In this way, you are not afraid of path problems and resource files being deleted by mistake.

First share a free website to get icons here: https://www.iconfinder.com/

Okay, let's demonstrate how to create resource files.

First, open the file menu, choose to create a new project or file, and select the resource file shown below.

If you are doing project development, the prefix indicates which type of resource file you need to add later. For example, you name the file, and then add the file-related, such as open the file icon, close the file icon, new file icon. To ensure the meaning of the prefix.

After this step, you will see more / folders.

Then you can click Add Files to add files.

If your resource file is not placed under the current project, it may prompt you whether to copy the resource file to the current project. It is best to copy to the current project.

The role of the alias is that if we modify the file name of the resource file, but we use the alias to refer to the resource file, then it will not cause an error. Using an alias can ensure that even if you modify the file name, it will not go wrong.

After the resource file is added, we can use the resource file. The path of the resource file can be obtained by right-clicking on the file and then clicking on the image below:

 

This is its path, of course, through observation we will find that in fact this path is-colon + prefix + file name

Then we set two icons in the code to take a look.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QIcon>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    
    ui->setupUi(this);
    //设置图标,使用资源文件。
    ui->actionOpen->setIcon(QIcon(":/Icon/Open.png"));          
    ui->actionNew->setIcon(QIcon(":/Icon/New.png"));
}

MainWindow::~MainWindow()
{
    delete ui;
}

This time we used the ui file when creating the project, so we quickly created some objects. We set atcionOpen and actionNew icons in the code. The results are as follows:

In fact, resource files will be compiled into cpp files. It can be seen under the project that it will indeed be compiled into a binary file.

Of course, the ui file will also be compiled into a cpp file, as follows:

With regard to resource files, so much has been introduced.

 

Published 242 original articles · Like 180 · Visits 160,000+

Guess you like

Origin blog.csdn.net/zy010101/article/details/105353251