The Qt Resource System

The Qt resource system is a platform-independent mechanism for storing binary files in the application's executable. This is useful if your application always needs a certain set of files (icons, translation files, etc.) and you don't want to run the risk of losing the files.

The resource system is based on tight cooperation between qmake, rcc (Qt's resource compiler), and QFile.

Resource Collection Files (.qrc)

 

The resources associated with an application are specified in a .qrc file, an XML-based file format that lists files on the disk and optionally assigns them a resource name that the application must use to access the resource.

Here's an example .qrc file:

 
Sélectionnez
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
    <file>images/copy.png</file>
    <file>images/cut.png</file>
    <file>images/new.png</file>
    <file>images/open.png</file>
    <file>images/paste.png</file>
    <file>images/save.png</file>
</qresource>
</RCC>

The resource files listed in the .qrc file are files that are part of the application's source tree. The specified paths are relative to the directory containing the .qrc file. Note that the listed resource files must be located in the same directory as the .qrc file, or one of its subdirectories.

Resource data can either be compiled into the binary and thus accessed immediately in application code, or a binary resource can be created and at a later point in application code registered with the resource system.

By default, resources are accessible in the application under the same file name as they have in the source tree, with a :/ prefix, or by a URL with a qrc scheme.

For example, the file path :/images/cut.png or the URL qrc:///images/cut.png would give access to the cut.png file, whose location in the application's source tree is images/cut.png. This can be changed using the file tag's alias attribute:

 
Sélectionnez
<file alias="cut-img.png">images/cut.png</file>

The file is then accessible as :/cut-img.png from the application. It is also possible to specify a path prefix for all files in the .qrc file using the qresource tag's prefix attribute:

 
Sélectionnez
<qresource prefix="/myresources">
    <file alias="cut-img.png">images/cut.png</file>
</qresource>

In this case, the file is accessible as :/myresources/cut-img.png.

Some resources need to change based on the user's locale, such as translation files or icons. This is done by adding a lang attribute to the qresource tag, specifying a suitable locale string. For example:

 
Sélectionnez
<qresource>
    <file>cut.jpg</file>
</qresource>
<qresource lang="fr">
    <file alias="cut.jpg"