Search code examples
qtqmlgradientrectangles

Gradient ignores parent rounded shape


I am trying to create a circle with a gradient color inside. The rectangle with radius below works fine, but as soon as I added the RadialGradient it goes back to square shape. I tried adding an opacity mask but it didn't work. What's wrong with this?

import QtQuick 2.0
import QtGraphicalEffects 1.0

Rectangle {
    id: light
    property string type: ""
    property bool connected: false
    property bool flagSet: false

    width: 50
    height: width
    radius: width / 2


    RadialGradient {
        anchors.fill: parent
        gradient: Gradient {
            GradientStop { position: 0.0; color: "green" }
            GradientStop { position: 0.5; color: "black" }
        }
    }


    OpacityMask {
        anchors.fill: parent
        source: light
        maskSource: Rectangle {
            height: light.height
            width: light.width
            radius: light.radius
        }
    }
}

Solution

  • This should do what you want:

        Rectangle {
            id: border
    
            width: light.width + 2
            height: width
            radius: width / 2
            color: "red"
    
            RadialGradient {
                id: light
                anchors.centerIn: parent
    
                width: 50
                height: width
    
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "green" }
                    GradientStop { position: 0.5; color: "black" }
                }
    
                layer.enabled: true
                layer.effect: OpacityMask {
                    id: mask
                    maskSource: Rectangle {
                        height: light.height
                        width: light.width
                        radius: width / 2
                    }
                }
            }
        }