Using Qt Resource Files

Sometimes when you write an application you might have some problems with your icons if you put all your images in a directory called “images” inside your application’s directory and then try to call the application from the command line somewhere else outside your application’s directory. The problem is that your icons will not appear, because the directory “images” is relative to your application’s directory.

To avoid this problem one could use the Qt Resource files to produce a .py module and then access all the icons from this module. First, you must create a .qrc file with the details of the resources you want to include. The .qrc file is a simple XML text file like the example below:

<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="appicon.png">images/appicon.png</file>
<file alias="exit.png">images/exit.png</file>
<file alias="fileexport.png">images/fileexport.png</file>
<file alias="fileimport.png">images/fileimport.png</file>
<file alias="fileopen.png">images/fileopen.png</file>
<file alias="help.png">images/help.png</file>
</qresource>
</RCC>

Then you must run pyrcc4 with the following command to produce a resource module from this resource file

pyrcc4 -o resources_rc.py resources.qrc

Finally, you import your resources_rc.py module into your main application and you can use images with the following syntax: QIcon(“:/help.png”), where the leading :/ informs PyQt that you are using a resource file.

You can also use resource files with Qt Designer as the following image suggests.

After the creation of your resources you can simple drag and drop an icon, for example, from the Resource Editor into the icon property of the object you want to add a icon in your Property Editor.

Have fun!

Advertisements

One Response to “Using Qt Resource Files”

  1. Hey, can you tell me the name of the used plugin for the sample code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: