Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

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. It obsoletes Qt 3's qembed tool and the image collection mechanism.

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:

 <!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:

 <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:

 <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, such as translation files and icons, many need to change based on the user's locale. This is done by adding a lang attribute to the 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>

If the user's locale is French (i.e., QLocale::system().name() returns "fr_FR"), :/cut.jpg becomes a reference to the cut_fr.jpg image. For other locales, cut.jpg is used.

See the QLocale documentation for a description of the format to use for locale strings.

External Binary Resources

For an external binary resource to be created you must create the resource data (commonly given the .rcc extension) by passing the -binary switch to rcc. Once the binary resource is created you can register the resource with the QResource API.

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");

Compiled-In Resources

For a resource to be compiled into the binary the .qrc file must be mentioned in the application's .pro file so that qmake knows about it. For example:

 RESOURCES     = application.qrc

qmake will produce make rules to generate a file called qrc_application.cpp that is linked into the application. This file contains all the data for the images and other resources as static C++ arrays of compressed binary data. The qrc_application.cpp file is automatically regenerated whenever the .qrc file changes or one of the files that it refers to changes. If you don't use .pro files, you can either invoke rcc manually or add build rules to your build system.

Building resources into an application

Currently, Qt always stores the data directly in the executable, even on Windows and Mac OS X, where the operating system provides native support for resources. This might change in a future Qt release.

Compression

Resources are compressed by default (in the ZIP format). It is possible to turn off compression. This can be useful if your resources already contain a compressed format, such as .png files. 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. You can specify the compression level and the threshold level to consider while compressing files, for example:

 rcc -compress 2 -threshold 3 myresources.qrc

Using Resources in the Application

In the application, resource paths can be used in most places instead of ordinary file system paths. In particular, you can pass a resource path instead of a file name to the QIcon, QImage, or QPixmap constructor:

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

See the Application example for an actual application that uses Qt's resource system to store its icons.

In memory, resources are represented by a tree of resource objects. The tree is automatically built at startup and used by QFile for resolving paths to resources. You can use a QDir initialized with ":/" to navigate through the resource tree from the root.

Qt's resources support the concept of a search path list. If you then refer to a resource with : instead of :/ as the prefix, the resource will be looked up using the search path list. The search path list is empty at startup; call QDir::addSearchPath() to add paths to it.

If you have resources in a static library, you might need to force initialization of your resources by calling Q_INIT_RESOURCE() with the base name of the .qrc file. For example:

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     Q_INIT_RESOURCE(graphlib);
     ...
     return app.exec();
 }

Similarly, if you must unload a set of resources explicitly (because a plugin is being unloaded or the resources are not valid any longer), you can force removal of your resources by calling Q_CLEANUP_RESOURCE() with the same base name as above.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 88
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 29
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le Qt Labs au hasard

Logo

Sémantique d'ordonnancement mémoire et opérations atomiques dans Qt

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web