How to embed an icon in a Qt application

This article demonstrates how to embed an icon in a Qt application. The approach holds for any type of an external file that needs to be embedded in an executable, such as an image (icon), a text file containing help etc. The embedding is accomplished by creating a Qt resource collection file *.qrc that lists the files that will become the part of the application source tree.

The problem will be demonstrated on an icon alignLeft.png that has to be embedded in an application. To achieve the embedding we need to perform the following steps in the Qt Creator:

1. In the project folder create a folder 'icons'. Place 'alignLeft.png' into the folder 'icons'.

2. To create a resource file: Right-click on the highlighted project -> Add New -> Qt -> Qt Resource file. Name the resource file 'qtresourceexample.qrc'.

3.To edit the resource file: Right-click on qtresourceexample.qrc -> Open With -> Plain Text Editor.

Enter the following lines into the resource file:

<!DOCTYPE RCC><RCC version="1.0">

4. Finally, check whether the resource file appeared in the *.pro file.

QT += widgets

    main.cpp \



5. Finally, to associate the icon with the action we need to call QAction::setIcon(QIcon).

Note for the users of the Qt Designer: If you used the UI designer for your widgets and wish to set the icon via the UI designer interface you need to perform the steps 1-4. In addition, you also need to do the following:

5. Run qmake

6. Switch to Action Editor at the bottom of the Designer, right-click on the action -> Edit... ->

7. In the 'Edit action dialog click on the button '...' -> Choose Resource...

8. In the Select Resource dialog expand , click on icons folder and choose the desired icon from the right window.

Tagged: Qt