1

I have this estructure on my application:

|-App
|
|-functions
|
|-ui
|--ui.py
|    
|images
|
|main.py

i have a functions folder with some scripts and a ui folder with the PyQt generated code on the ui.py file.

and a main.py file that loads the ui.py to show the interface and ui.py loads some images from the "images" folder on the root.

if I execute my script directly on python (double clic on main.py file), the images wont show..

But if I use the terminal with "python main.py" the images show correctly.

The references on ui.py are like:

icon.addPixmap(QtGui.QPixmap(_fromUtf8("images/flags/MXN.png"))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Rafael Carrillo
  • 2,772
  • 9
  • 43
  • 64
  • Are you sure you execute with the same python version with the double clic and the terminal ? What is the first line of your main.py ? On what OS ? – Nicolas Barbey Aug 07 '12 at 09:15

1 Answers1

8

Use the Qt Designer Resource System to create a resource file for the images.

Then use PyQt's pyrcc tool to convert the Qt resource file into a python module.

NB: The python resource module should go in the same directory as your ui files. So if you created the resource file App/resources.qrc in Qt Designer, you should then convert it like this:

pyrcc5 -o App/ui/resources_rc.py App/resources.qrc

The equivalent tool for PySide (Qt4) was pyside-rcc. For PySide2/PySide6, the Qt rcc tool itself has an option to produce python output:

rcc -g python -o App/ui/resources_rc.py App/resources.qrc

If you're not using Qt Designer, see the standalone example below. The following files all go together in the same root directory. If the image files are in a sub-directory, the qrc file must use relative paths (e.g. subdir/image.jpg). The resource_rc module is generated by executing the following command within the root directory:

pyrcc5 -o resource_rc.py resource.qrc

To make the resources accessible, you must import the generated module:

import resource_rc

The files within the resource are then accessed by prefixing ":/" to the path (e.g. ":/image.jpg" in the example below).

resource.qrc

<RCC>
    <qresource>
        <file>image.jpg</file>
    </qresource>
</RCC>

main.py:

from PyQt5 import QtGui, QtWidgets
import resource_rc

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.label = QtWidgets.QLabel()
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.label)
        self.label.setPixmap(QtGui.QPixmap(':/image.jpg'))

app = QtWidgets.QApplication(['Test'])
window = Window()
window.show()
app.exec_()

UPDATE:

PyQt6 has now removed the pyrcc tool (see: How can resources be provided in PyQt6 (which has no pyrcc)?).

ekhumoro
  • 115,249
  • 20
  • 229
  • 336