Brykyz
Brykyz

Reputation: 657

QML Change color of rectangle by text

I am trying to learn QML and I can't figure out how to change color of rectangle by text, that is written into it.

Rectangle {
     width: 50; height: 50; color: red
     Text {
         text: "20%"
         font.pointSize:10
     }
 }

It should do something like when text is > 10%, color of rectangle should be green, > 50% should be orange and so on.

I read tutorial by Qt, but I can't get it. I tried to do it with onTextChange, but somehow it didn't work.

Thank you for help!

Upvotes: 0

Views: 1787

Answers (1)

derM
derM

Reputation: 13691

There are tons of options. A simple one would be to bind the color to an expression that selects a value from a JS Object:

Rectangle {
    width: 100
    height: 100
    color: {
        "text1" : 'red',
        "text2" : 'blue',
        "text3" : 'orange'
    }[myText.text]

    Text {
        id: myText
        text: "text2"
    }
}

Documentation suggests, that the binding to a conditional expression like this might be more efficient:

   Rectangle {
    width: 100
    height: 100
    color: (myText.text === "text1"
            ? 'green'
            : myText.text === "text2"
            ? 'red'
            : myText.text === "text3"
            ? 'orange'
            : 'black')

    Text {
        id: myText
        text: "text2"
    }
}

but I think it is harder to read.

OFC, you can also use the onTextChanged like this:

Rectangle {
    id: rect
    width: 100
    height: 100
    color: 'blue'

    Text {
        id: myText
        text: "text2"
        onTextChanged: {
            if (text === "text1") { rect.color = 'green'; return; }
            if (text === "text2") { rect.color = 'blue'; return; }
            if (text === "text3") { rect.color = 'orange'; return; }
        }
    }
}

But I would encourage you to try to do as much as possible declarative (with bindings) - especially when you learn QML you might be tempted to fall back on JS and develop a (IMHO) bad QML coding style.

Upvotes: 2

Related Questions