Dynamic Color assignment and CSS
-
Hello,
I'm using PyQt5 to play around with some guis. I previously used tkinter, but when I learned that you can import a CSS file, I flocked to qt. So with tkinter I can:
from pathlib import Path def get_colors(): return Path(Path('~/.cache/wal/colors').expanduser()).read_text().split('\n')
and that returns a list I can call like:
>>> colors = get_colors() >>> colors[0] #040405
with qt, I have an external css file so I can quickly change it, or import it to different apps. I import it using:
self.setStyleSheet(open('myCSS.css').read())
Is there a way I can import the colors in a similar manner in qt and use them in the separate stylesheet?
-
Hi and welcome to devnet,
The way you load the colors does not need to change. However I have the feeling that it is not the main question.
Do you want to replace values in the stylesheet content ?
-
@maxTim
I'm not clear what you are asking/seeking to do. But from the title, "Dynamic Color assignment and CSS", if you are wanting to control which colors are used in the stylesheet you need to process theopen('myCSS.css').read()
to do some kind of substitution/insertion of colors as desired, passing the result on to thesetStyleSheet()
. -
And this is what I came up with:
from pathlib import Path class Menu(QDialog): def __init__(self): super().__init__() self.initUI() def get_colors(self): colors = Path(Path('~/.cache/wal/colors').expanduser()).read_text().split('\n') css = open('vMenu.css').read() for x in range(len(colors)): css = css.replace(f'color{x}', colors[x]) return css def initUI(self): # [ . . . ] self.setStyleSheet(self.get_colors())
vMenu.css
QDialog { background-color: color0; } QPushButton, QGroupBox, QLabel { font-family: 'Swiss911 XCm BT'; font-size: 24px; border: 0px; color: color2; } QPushButton { text-align: right; } QLabel#title { font-size: 32px; text-align: center; }
colors file
#040405 #5B5F5B #9B544A #6E8B6A #ABA764 #5D758B #709996 #c3c9c3 #888c88 #5B5F5B #9B544A #6E8B6A #ABA764 #5D758B #709996 #c3c9c3