1

I have what looks like a very simple problem: I want to design a QLabel whose value changes dynamically (no issue here) and whose background color changes accordingly (this is the issue).

Of course, I know I can do something like that (pseudo code):

function on_new_value(value):
    label.setText(value)
    if value>10:
        label.setBackgroundColor(RED)
    else if value<0:
        label.setBackgroundColor(RED)
    else:
        label.setBackgroundColor(GREEN)

But that kind of mixes model and view. What I'd like, ideally, would be to be able to use an extended version of Qt Stylesheets as follows:

QLabel { background: green; }
QLabel { if value>10: background: red; }
QLabel { if value<0: background: red; }

Obviously, that is not possible. But I'm wondering if Qt allows for something close in order to embbed (for instance in a class) a graphic behaviour based on a value.

I know about QPalette, but the style condition is only about the widget Active/Disable state, not its "value".

In other words, I'm looking for sort of a ValueDependantStyle class or somehting close.

Any pointers? Am I looking at this all wrong?

Edit: in case this is important, I'm developping with PyQt5.

Silverspur
  • 891
  • 1
  • 12
  • 33
  • If you really want to separate the styling and the model, you could extend QLabel into your own class and set the style within the class. Is this what you are looking for? – Aditya Mar 19 '21 at 15:34
  • I would do that, but in the full app, there are several QLabels and their value-dependant styles are dynamically created by the user. So I cannot hard-code the style, but I'm looking for a structure that can host it, ideally in a Qt-compatible way. – Silverspur Mar 19 '21 at 21:25

1 Answers1

2

You could use a "model property" on the label, that defines the color in a style sheet (cf. Qt Style Sheet Reference about properties):

function on_new_value(value):
    label.setText(value)
    if value>10:
        label.setProperty("HasError", "true")
    else if value<0:
        label.setProperty("HasError", "true")
    else:
        label.setProperty("HasError", "false")
QLabel[HasError="false"] { background: green; }
QLabel[HasError="true"] { background: red; }
king_nak
  • 11,313
  • 33
  • 58