Search code examples
qmlopacity

How to change QML Rectangle opacity without affecting color of what's on it?


I want to set only the opacity on my Rectangle, but the text which shows on top of it also becomes transparent.

How can I set just the opacity for the background Rectangle without changing the opacity of the text?

Rectangle {
    id: button
    color: "black"
    opacity: 0.3
    width: parent.width
    height: 35

    Text {
        anchors.centerIn: parent
        text: qsTr("text")
        color: "white"
        font.pixelSize: 25
    }
}

Solution

  • This is explained in the documentation for opacity:

    When this property is set, the specified opacity is also applied individually to child items. This may have an unintended effect in some circumstances. For example in the second set of rectangles below, the red rectangle has specified an opacity of 0.5, which affects the opacity of its blue child rectangle even though the child has not specified an opacity.

    You can either move the Text item out:

    Rectangle {
        id: button
        color: "black"
        opacity: 0.3
        width: parent.width
        height: 35
    }
    
    Text {
        anchors.centerIn: button
        text: qsTr("text")
        color: "white"
        font.pixelSize: 25
    }
    

    Or give the Rectangle a transparent colour instead of changing the opacity:

    Rectangle {
        id: button
        color: "#33000000" // form: #AARRGGBB
        width: parent.width
        height: 35
    
        Text {
            anchors.centerIn: parent
            text: qsTr("text")
            color: "white"
            font.pixelSize: 25
        }
    }