Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

python - How to load image resources with PyQt?

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"))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

UPDATE:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...