Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set label font color from hex value

Tags:

python

pyqt

I am trying to set a font color on a QLabel to a hex value received from the server.

Currently I am just setting the text of the label but have no idea how to set the font color.

def set_stat_lbl(self):
    palette = QPalette()
    palette.setColor(QPalette.Foreground, self.stat_value_color)
    self.stat_lbl.setText(_translate("rep_stat", self.stat_name, None))
    self.stat_lbl.setPalette(palette)

Where self.stat_value_color would be a hex string like #fb0000. The above code clearly doesn't work as it wants a color not a string.

like image 358
Jared Mackey Avatar asked Sep 05 '25 03:09

Jared Mackey


1 Answers

You can also instantiate a QColor with the hex string.

palette = self.stat_lbl.palette()
color = QColor('#112233')
palette.setColor(QPalette.Foreground, color)
self.stat_lbl.setPalette(palette)

Also, you can use css directly on the widget, as opposed to having to construct it each time when setting the text:

self.stat_lbl.setStyleSheet('QLabel {color: #112233;}')
self.stat_lbl.setText('This is colored text')
like image 117
Brendan Abel Avatar answered Sep 07 '25 21:09

Brendan Abel