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)?).