MaKaNu
MaKaNu

Reputation: 1008

Return of the path of ":/filename" in pyqt function QIcon

I try to understand the code of someone else and he is using the QIcon function to set the WindowIcon. As I used the QIcon before, I used an absolute path inside my programm like this:

...
app = QApplication([])
    app.setWindowIcon(QIcon('.\\MyApp\\data\\Logo.png'))
    start_window = StartWindow()
    start_window.show()
    app.exit(app.exec_())
...

In his Code he uses a utility function to call QIcon to be able to change the filename. But instead of an absolute path he is calling QIcon(':/' + filename).

I am not able to achieve the same results with this "relative" path. I might get anything else wrong or misunderstand the use of :/

Upvotes: 3

Views: 884

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

The prefix ":/" is a virtual path that only recognizes the elements of Qt since it is based on The Qt Resource System, in C++ what it does is to embed the resource (images, files or any type of static file) in the binary . In python that idea is also extrapolated generating a .py using the resources as a source.

In C++ the rcc tool is used and in PyQt5 pyrcc5 is used (in PyQt4 pyrcc4 is used), in PySide2 you can use pyside2-rcc or rcc.

The steps to use it are simple:

  1. create a .qrc, you can do that with Qt Designer (check the menu View-> Resource Browser), although the format is a simple xml.

myresource.qrc

```
<RCC>
  <qresource prefix="/">
    <file>Logo.png</file>
  </qresource>
</RCC>
```
  1. You convert it to .py using pyrcc5 (or the other tools):

    pyrcc5 myresource.qrc -o myresource_rc.py
    
  2. Then you import it into the file where you are going to use it:

    main.py

    # ...
    import myresource_rc
    # ...
    
  3. Use it:

    app.setWindowIcon(QIcon(':/Logo.png'))
    

See The PyQt5 Resource System

Upvotes: 3

Related Questions