Friday, March 2, 2012

adding icons to an application with Qt Creator

The book "C++ GUI Programming with Qt 4" gives a short description of how to use a resource file to include images into the executable which can then (for example) be used as icons. The example given is clear by itself but when using the latest QtCreator version (2.4.1) things turn out to work just a little bit different. Furthermore a resource file as given in the book does not load correctly in QtCreator.

To add image resources I now do this:
1. Create a new resource file by clicking File -> New File or Project and then Choose Qt resource file.
2. Add a prefix for example /icons
3. Add your images files for example: images/icon.png (with a images a subdirectory in your project folder
4. Refer to these resources in your code as ":/icons/images/icon.png"

The changed point compared to the resource file example in the book is the prefix. You now have to add a prefix which (probably) did not exist in the past. In the example application (called "application") that comes with QtCreator the prefix that is used is simply "/".

Adding the icon to a widget (e.g. your main window) is now simple:

setWindowIcon(QIcon(":/icons/images/icon.png"));

And as requested some screen shots.

Step 1, creating a new resource file:


Step 2, add a prefix:


Simply type over the default prefix label generator by QtCreator. Your prefix will appear in the main window:



Step 3, add image files (after selecting the prefix in the main window):


The final result then looks something like this:

7 comments: