The addition and use of the resource file (qrc) for Qt learning

Table of contents

foreword

Add resource file

Use of resource files

foreword

When the Qt project is packaged and sent to others, some pictures may not be displayed or one picture cannot be loaded, then it may be that other people’s computers do not have these picture resources, or the source program loads pictures using absolute paths. The writing method is inconsistent with the absolute path of the picture on other people’s computers, so it cannot be loaded.

This problem can be solved by adding resource files through Qt, and when the project is packaged and sent to others, there is no need to package the pictures together, which can save a lot of space. This article is to introduce how Qt adds resource files and uses them.

Add resource file

Right-click the project folder -> click Add New File

Select Qt->Qt Resource File->choose in turn

Give the resource a name, click Next, and then click Finish.

First choose to add a prefix, and then change the prefix to what you need, or directly use / 

Then select Add File, and then add the desired image to it, Ctrl+s to save.

You can see the added image resources on the project side, and the resource addition is complete.

If there are new pictures to be added later, you can right-click the qrc file, then Open With –> Resource Editor, you can go back to the interface for adding files. 

Use of resource files

Image path writing: colon + prefix added before + the folder where the image is located + /xxx.png

For example: :/image/design.png

Take QLabel and QPushButton as examples to add pictures. code show as below:

//label loading image 
QLabel *imgLabel = new QLabel(this);
imgLabel->resize(64,64);
imgLabel->move(200,100);
imgLabel->setPixmap(QPixmap( ":/image/design.png" ).scaled( 64 , 64 )); //The image size is changed to 64x64

//Button loading image 
QPushButton *imgBtn = new QPushButton(this);
imgBtn->resize(64,64);
imgBtn->move(200,300);
imgBtn->setStyleSheet("QPushButton {background-image: url(:/image/edit.png)}");

Effect

After the project is packaged and released, the image folder is not needed, and all the image information is stored in the xxx.qrc file in binary form.

Leave a Comment

Your email address will not be published. Required fields are marked *