Qt 资源系统

The Qt resource system is a platform-independent mechanism for shipping resource files in an application. Use it if your application always needs a certain set of files (like icons, translation files, images), and you don't want to use system-specific means to package and locate these resources.

Most commonly, the resource files are embedded into your application executable, or in libraries and plugins that are loaded by the application executable. Alternatively, the resource files can also be stored in an external resource file .

The resource system is based on tight cooperation between Qt's rcc resource compiler, the build system, and the Qt runtime API.

注意: Currently, the Qt resource system does not make use of any system-specific capabilities for handling resources, such as the ones on Windows, macOS, and iOS. This might change in a future Qt release.

Qt 资源编译器 RCC

The RCC (资源编译器) command line tool reads resource files and generates either a C++ or Python source file, or an .rcc 文件。

The list of files and related metadata is passed to rcc in the form of a Qt 资源集合文件 .

By default, rcc will generate C++ source code that is then compiled as part of an executable or library. The -g python option generates Python source code instead. The -binary option generates a binary archive that is by convention saved in an .rcc file and can be loaded at runtime.

注意: While it is possible to run rcc from the command line, this is typically best left to a build system. See also the sections about qmake and CMake 下文。

Qt 资源集合文件 .qrc

A .qrc file is an XML document that enumerates local files to be included as runtime resources. It serves as input to rcc .

这里是范例 .qrc 文件:

<RCC>
    <qresource prefix="/">
        <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>
					

每个 <file> element in the XML identifies a file in the application's source tree. The path is resolved relative to the directory containing the .qrc 文件。

The path is also used by default to identify the file's content at runtime. That is, the file titlebarLeft.png will be available in the resource system as :/res/titlebarLeft.png or qrc:/res/titlebarLeft.png . To override this default run-time name, see 前缀 and 别名 .

Qt Creator , Qt Design Studio , Qt Designer ,和 Qt Visual Studio Tools allow you to create, inspect and edit .qrc files through a convenient user interface. Except for Qt Designer , they also provide wizards for projects using the Qt resource system.

构建系统集成

The processing of resource files with rcc is typically done at the time the application is built. Several build tools have dedicated support for this, including CMake and qmake .

CMake

CMAKE_AUTORCC is enabled, you can just add .qrc files as sources to your executable or library. The referenced resource files will then be embedded into the binary:

set(CMAKE_AUTORCC ON)
qt_add_executable(my_app
    application.qrc
    main.cpp
)
					

CMake 的 AUTORCC 文档编制 了解有关 AUTORCC 的更多细节。

An alternative to AUTORCC is using Qt6Core's CMake function qt_add_resources , which gives more control over the creation of resources. For example, it allows you to specify the content of the resource directly in the project file without writing a .qrc file first:

qt_add_resources(my_app "app_images"
    PREFIX "/"
    FILES
        images/copy.png
        images/cut.png
        images/new.png
        images/open.png
        images/paste.png
        images/save.png
)
					

最后, qt_add_qml_module allows you to embed Qt Quick resources into the resource system of your application. The function is defined in the Qml 组件对于 Qt6 CMake package.

qmake

qmake 支持处理资源采用 RESOURCES 变量。若添加 .qrc file path to the variable, the listed resource files will be embedded into the generated library or executable:

RESOURCES = application.qrc
					

This creates a resource of several .png files, that are addressable like this: ":/res/titlebarLeft.png" .

If the directory layout of the files you want to embed into the resource doesn't match the expectations of the application, you can specify resources.base . base is a path prefix that denotes the root point of the file's alias. In the example above, if resources.base 被设为 "res" ,那么 titlebarLeft.png is addressable as ":/titlebarLeft.png" .

运行时 API

Qt API that deals with iterating and reading files has built-in support for the Qt Resource System. You can pass a resource path instead of a local file path to QFile and QDir , but also for instance to the QIcon , QImage ,和 QPixmap 构造函数:

    cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
					

The : prefix makes it explicit that "/images/cut.png" should be loaded from the Qt Resource System.

You can also reference the Qt resource system through a QUrl 。使用 qrc scheme in this case:

    QQmlApplicationEngine engine;
    engine.load(QUrl("qrc:/myapp/main.qml"));
					

高级话题

前缀

A .qrc file can set a prefix to be added to each local file name, given in a <file> element, to get the name by which the file shall be known within the resource system.

Prefixes allow you to structure the resources, avoiding clashes between resource files added through different .qrc files in different libraries or plugins.

注意: The /qt and /qt-project.org prefixes are reserved for documented use cases in Qt. The qt.conf file is for instance looked up in :/qt/etc/qt.conf or qrc:/qt/etc/qt.conf .

别名

Sometimes it is convenient to make a resource file available under a different path at runtime. .qrc files allow this by setting an alias 属性:

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

The file is from the application then only accessible as :/cut-img.png or qrc:/cut-img.png .

丢弃文件内容

Sometimes you want to add a file node to the resource file system but don't actually want to add the file contents. .qrc files allow this by setting the empty attribute to true .

<file empty="true">Button.qml</file>
					

The resulting file is then still accessible from the application, but its contents are empty.

This is useful to strip QML source code from an application binary.

注意: If you omit the QML source code from the binary, the QML engine has to rely on the compilation units created by qmlcachegen or qmlsc . Those are tied to the specific version of Qt they were built with. If you change the version of Qt your application uses, they can't be loaded anymore.

语言选择器

Some resources need to change based on the user's locale, such as translation files or icons. 资源集合文件 support this through a lang 属性到 qresource tag, specifying a suitable locale string. For example:

<qresource>
    <file>cut.jpg</file>
</qresource>
<qresource lang="fr">
    <file alias="cut.jpg">cut_fr.jpg</file>
</qresource>
					

若用户的区域设置为法语 (即 QLocale::system ().language() 为 French), :/cut.jpg or qrc:/cut.jpg 变为引用针对 cut_fr.jpg 图像。对于其它区域设置, cut.jpg 被使用。

QLocale 文档编制了解区域设置字符串所用格式的描述。

QFileSelector 了解选择特定区域设置资源的额外机制。

嵌入大文件

默认情况下, rcc embeds the resource files into executables in the form of C++ arrays. This can be problematic especially for large resources.

If the compiler takes too long, or even fails because of memory overflow, you can opt into a special mode where the resources are embedded as part of a two-step process. The C++ compiler only reserves enough space in the target executable or library for the resources. The actual embedding of the resource file's content and metadata is then done after the compilation and linking phase, through another rcc call.

对于 CMake,需要使用 qt_add_big_resources 函数。

外部资源文件

An alternative to embedding the resource files into the binary is to store them in a separate .rcc 文件。 rcc allows this with the -binary option. Such a .rcc file must then be loaded at runtime with QResource .

For example, a set of resource data specified in a .qrc file can be compiled in the following way:

rcc -binary myresource.qrc -o myresource.rcc
					

In the application, this resource would be registered with code like this:

QResource::registerResource("/path/to/myresource.rcc");
					

If you use CMake, you can use the qt_add_binary_resources function to schedule the rcc call above:

qt_add_binary_resources(resources application.qrc DESTINATION application.rcc)
add_dependencies(my_app resources)
					

Qt for Python 应用程序中的资源

The resource collection file is converted to a Python module by using the resource compiler rcc :

rcc -g python mainwindow.qrc > mainwindow_rc.py
					

The module can then be imported in the application:

import mainwindow_rc.py
					

压缩

rcc attempts to compress the content to optimize disk space usage in the final binaries. By default, it will perform a heuristic check to determine whether compressing is worth it and will store the content uncompressed if it fails to sufficiently compress. To control the threshold, you can use the -threshold option, which tells rcc the percentage of the original file size that must be gained for it to store the file in compressed form.

rcc -threshold 25 myresources.qrc
					

The default value is "70", indicating that the compressed file must be 70% smaller than the original (no more than 30% of the original file size).

It is possible to turn off compression if desired. This can be useful if your resources already contain a compressed format, such as .png files, and you do not want to incur the CPU cost at build time to confirm that it can't be compressed. Another reason is if disk usage is not a problem and the application would prefer to keep the content as clean memory pages at runtime. You do this by giving the -no-compress command line argument.

rcc -no-compress myresources.qrc
					

rcc also gives you some control over the compression level and compression algorithm, for example:

rcc -compress 2 -compress-algo zlib myresources.qrc
					

它也是可能的,使用 threshold , compress ,和 compress-algo 作为属性在 .qrc file 标签。

<qresource>
    <file compress="1" compress-algo="zstd">data.txt</file>
</qresource>
					

The above will select the zstd algorithm with compression level 1.

rcc supports the following compression algorithms and compression levels:

  • best : use the best algorithm among the ones below, at its highest compression level, to achieve the most compression at the expense of using a lot of CPU time during compilation. This value is useful in the XML file to indicate a file should be most compressed, regardless of which algorithms rcc 支持。
  • zstd : use the Zstandard library to compress contents. Valid compression levels range from 1 to 19, 1 is least compression (least CPU time) and 19 is the most compression (most CPU time). The default level is 14. A special value of 0 tells the zstd library to choose an implementation-defined default.
  • zlib : use the zlib library to compress contents. Valid compression levels range from 1 to 9, with 1 applying the least compression (least CPU time) and 9 the most compression (most CPU time). The special value 0 means "no compression" and should not be used. The default is implementation-defined, but usually is level 6.
  • none : no compression. This is the same as the -no-compress 选项。

Support for both Zstandard and zlib are optional. If a given library was not detected at compile time, attempting to pass -compress-algo for that library will result in an error. The default compression algorithm is zstd if it is enabled, zlib 若不。

嵌入资源的明确加载和卸载

Resources embedded in C++ executable or library code are automatically registered to the Qt resource system in a constructor of an internal global variable. Since the global variables are initialized before main() runs, the resources are available when the program starts to run.

When embedding resources in static libraries, the C++ linker might remove the static variables that register the resources. If you embed resources in a static library, you therefore need to explicitly register your resources by calling Q_INIT_RESOURCE () with the base name of the .qrc 文件。例如:

MyClass::MyClass() : BaseClass()
{
    Q_INIT_RESOURCE(resources);
    QFile file(":/myfile.dat");
    ...
}
					

You can also explicitly remove registered resources from the application, for instance when unloading a plugin. Use Q_CLEANUP_RESOURCE () for this.

Note: As the resource initializers generated by rcc are declared in the global namespace, your calls to Q_INIT_RESOURCE () 和 Q_CLEANUP_RESOURCE () need to be done outside any namespace.