Search code examples
pyqt5qtstylesheets

How to add a .qss file from resource


my Problem is the following: I'm working with PyQt5 and I want to use an external stylesheet, meaning I've a .qss that is referenced in my .qrc file and I want to apply this in my code.

Now my question is how am I going to load this file and what format whatsoever does this need. For example

sty_f = open(":/Style/style.qss","r")

leads to a FileNotFound error. Although according to the resource file it should be there.

sty_f = QtCore.QFile(":/Style/style.qss")
sty_f.open(QtCore.QIODevice.ReadOnly)

on the other hand has no problem to find the referenced file but produces a QByteArray that APP.setStyleSheet(sty_f.readAll()) cannot use. Just converting it to a str APP.setStyleSheet(str(sty_f.readAll())) results in a Could not parse application stylesheet error.

And last but not least:

sty_f = open("PATH/style.qss","r")
APP.setStyleSheet(sty_f.read())

works. Now is there a way to make it working using the resource file as well? And what part might be flawed as all of them work but not at the same time?

Update: What works as well is:

sty_f = QtCore.QFile(":/Style/style.qss")
sty_f.open(QtCore.QIODevice.ReadOnly)
APP.setStyleSheet(((sty_f.readAll()).data()).decode("latin1"))

But still the question is there a better way to do so as converting this mess doesn't feel to be the optimal solution.


Solution

  • Some Qt APIs support reading resources directly, but otherwise you will have to read them yourself. This also entails using the Qt IO classes, since those are the only things that can understand resource paths.

    For the specific case of reading a qss file, you can ignore the encoding, since the file should only contain ascii. So this seems about a simple as you can get:

    stream = QtCore.QFile(resource_path)
    stream.open(QtCore.QIODevice.ReadOnly)
    widget.setStyleSheet(QtCore.QTextStream(stream).readAll())