qtqstyle

Qt: Style depending on label value


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.


Solution

  • 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; }