Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Embedding Resources

So far in this chapter, we have talked about accessing data in external devices, but with Qt it is also possible to embed binary data or text inside the application's executable. This is achieved using Qt's resource system. In other chapters, we used resource files to embed images in the executable, but it is possible to embed any kind of file. Embedded files can be read using QFile just like normal files in the file system.

Resources are converted into C++ code by rcc, Qt's resource compiler. We can tell qmake to include special rules to run rcc by adding this line to the .pro file:

RESOURCES = myresourcefile.qrc

The myresourcefile.qrc file is an XML file that lists the files to embed in the executable.

Let's imagine that we are writing an application that keeps contact details. For the convenience of our users, we want to embed the international dialing codes in the executable. If the file is in the datafiles directory in the application's build directory, the resource file might look like this:


From the application, resources are identified by the :/ path prefix. In this example, the dialing codes file has the path :/datafiles/phone-codes.dat and can be read just like any other file using QFile.

Embedding data in the executable has the advantage that it cannot get lost and makes it possible to create truly stand-alone executables (if static linking is also used). Two disadvantages are that if the embedded data needs changing the whole executable must be replaced, and the size of the executable will be larger because it must accommodate the embedded data.

Qt's resource system provides more features than we presented in this example, including support for file name aliases and for localization. These facilities are documented at http://doc.trolltech.com/4.3/resources.html.

  • + Share This
  • 🔖 Save To Your Account