How to set relative path in Qt Stylesheet?

Viewed 600

I'm trying to add a picture to a button in PyQt5 using stylesheet. It is working fine if I use an absolute path to the picture, but I need to use a relative path instead. I've tried the pythonic way (the commented out part), but it is not working probably because of the backslashes. I know about Qt resources but I don't understand how to use them. link

import os, sys
from PyQt5.QtWidgets import *

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        #scriptDir = os.path.dirname(os.path.realpath(__file__))
        #pngloc = (scriptDir + os.path.sep + 'resources' + os.path.sep + 'min.png')

        button1 = QPushButton("", self)
        button1.setStyleSheet('QPushButton {'
                               'background-image: url(e:/new/resources/min.png);'
                               '}')

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
1 Answers

If you want to use relative paths then a good option is to use the Qt Resource System which creates virtual paths. The advantage of .qrc is that they allow the application not to depend on local files since the resources are converted to python code.

For this case the following .qrc can be used:

resource.qrc

<!DOCTYPE RCC><RCC version="1.0">
  <qresource>
    <file>resources/min.png</file>
  </qresource>
</RCC>

So you need to convert the .qrc to .py using pyrcc5:

pyrcc5 resource.qrc -o resource_rc.py

or

python -m PyQt5.pyrcc_main resource.qrc -o resource_rc.py

Then you need to import the file into the script:

main.py

import os, sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton

import resource_rc


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        button1 = QPushButton(self)
        button1.setStyleSheet(
            """QPushButton {
                background-image: url(:/resources/min.png);
            }"""
        )


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
├── main.py
├── resource.qrc
├── resource_rc.py
└── resources
    └── min.png
Related