Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for color equality in QML?

Tags:

qt

qml

qtquick2

I have the following code:

Item {
    width:  fos.width; height: fos.height

    Rectangle {
        id: fos
        width: 120; height: 120
        color: "red"

        MouseArea {
            anchors.fill: parent
            onClicked: {
                if (fos.color == "red") fos.color = "gray"
                else fos.color = "red"
            }
        }
    }
}

I want to change the Rectangle color when the MouseArea is clicked. However, the code does not work. Where is my fault?

like image 314
Mr.Tu Avatar asked Sep 15 '25 10:09

Mr.Tu


1 Answers

The problem is your test:

fos.color == "red" 

"red" is only a name or alias for "#ff0000". You can see it by printing the value, i.e.:

//...
MouseArea {
    anchors.fill: parent
    onClicked: {
        console.log('fos.color:', fos.color); // fos.color: #ff0000
        //...
    }
}

According to documentation you should use Qt.colorEqual() or test against "#ff0000" for color equality.

like image 62
hooblei Avatar answered Sep 18 '25 10:09

hooblei