Importing resource file to PyQt code?

In addition to the above wonderful answers, if you would also like the ability to set the icon from within QtCreator itself (instead of having to do the say setWindowIcon(QIcon('://images/app_icon.ico')) line in code), you do this:

pyrcc5 -o resources_rc.py resources.qrc cd ui pyuic5 -o dialog.py dialog.ui

(Note that pyuic5 automatically imports resources_rc and not resources for some reason; hence the new name specified above)

Where you've made sure that:

...
</tabstops>
 <resources>
  <include location="../resources.qrc"/>
 </resources>
<connections>
...

appears approximately there (between tabstops and connections) in your dialog.ui file. I think to get it there automatically, you can create a dummy C++ project and add your .ui files to the dummy project, then add a new Qt Resource file to the project. When your done, you can delete everything leaving the .ui files and the .qrc file. If you happen to copy resources.qrc to another directory, then closing and re-opening the dialog.ui file will prompt you for where the new location is.

Now you can set the resources from the Property explorer on in QtCreator: windowIcon > Choose Resource > (click on the root) > (your files should show up now) > (select app_icon.ico).


I just checked a newly created mainwindow.ui, if you open up the file in Text Edit mode in Qt Creator it shows you where the <resource /> stub is. Simply insert there (using some other program) For some reason opening up the newly created .ui file in Notepad++ was not showing it.


When closing and re-opening files, you must actually close the file (not "Reload" - doesn't work) and open it again. Then the resource root in "add image from resources" dialog will be non-empty.


In PyQt5, we should write in comand line

pyrcc5 -o resources.py resource/resources.qrc

Because, we need to generate a resource.py to import in the code. Now we can type

import resources

in our python code


For pyqt you have to use pyrcc4, which is the equivalent of rcc for python.

pyrcc4 -o resources.py resources.qrc

This generates the resources.py module that needs to be imported in the python code in order to make the resources available.

import resources

To use the resource in your code you have to use the ":/" prefix:

Example

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import resources

pixmap = QPixmap(":/newPrefix/download.jpeg")

See The PyQt4 Resource System and The Qt Resource System