如何使用PyQt加载图像资源? [英] How to load image resources with PyQt?
问题描述
我的应用程序具有以下结构:
I have this estructure on my application:
|-App
|
|-functions
|
|-ui
|--ui.py
|
|images
|
|main.py
我有一个包含一些脚本的功能文件夹,以及一个在ui.py文件上包含PyQt生成的代码的ui文件夹.
i have a functions folder with some scripts and a ui folder with the PyQt generated code on the ui.py file.
和一个main.py文件,该文件加载ui.py以显示界面,而ui.py则从根目录的"images"文件夹中加载一些图像.
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.
如果我直接在python上执行脚本(main.py文件中为double clic),则不会显示图片.
if I execute my script directly on python (double clic on main.py file), the images wont show..
但是如果我将终端与"python main.py"一起使用,则图像会正确显示.
But if I use the terminal with "python main.py" the images show correctly.
ui.py上的引用类似于:
The references on ui.py are like:
icon.addPixmap(QtGui.QPixmap(_fromUtf8("images/flags/MXN.png"))
推荐答案
使用 Qt设计器资源系统,为图像创建资源文件.
Use the Qt Designer Resource System to create a resource file for the images.
然后使用 PyQt的pyrcc工具来转换Qt资源文件放入python模块.
Then use PyQt's pyrcc tool to convert the Qt resource file into a python module.
NB:python资源模块应与ui文件位于同一目录中.因此,如果您在Qt Designer中创建了资源文件 App/resources.qrc
,则应按如下所示进行转换:
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
PySide(Qt4)的等效工具是 pyside-rcc
.对于PySide2/PySide6,Qt rcc
工具本身具有生成python输出的选项:
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
更新:
PyQt6现在已删除了pyrcc工具(请参阅:如何在PyQt6(不包含pyrcc)中提供资源?).
PyQt6 has now removed the pyrcc tool (see: How can resources be provided in PyQt6 (which has no pyrcc)?).
这篇关于如何使用PyQt加载图像资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!