Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top