How to use the LinearGradient in a ShapePath?

Viewed 474

I'd like to draw a gradient inside a custom shape. I have used the property fillColor previously and try to use the property fillGradient now. The shape is fine I would say - at least it looks like expected :) What isn't fine in any way is this gradient thing. It just doesn't look anything like expected.

Here is what I want to do. This should run as it is in Qt Design Studio.

import QtQuick 2.15 
import QtQuick.Controls 2.15 
import QtQuick.Shapes 1.15 

Rectangle {
    id: btn
    color: "white"

    readonly property alias fieldHeight: p.fieldHeight

    Shape {
        ShapePath {
            id: p
            property int r: 172
            property int fieldWidth: 123
            property int fieldHeight: 79
            property int deltaX: 30
            startX: 0
            startY: 0
            strokeColor: "black"
            strokeStyle: ShapePath.SolidLine
            fillGradient: LinearGradient {
                GradientStop {
                    position: 0
                    color: "#6c6c6c"
                }
                GradientStop {
                    position: 1
                    color: "#000000"
                }
            }
            PathArc {
                id: upperBorder
                x: p.fieldWidth
                y: 0
                radiusX: p.r
                radiusY: p.r
            }
            PathLine {
                x: p.fieldWidth - p.deltaX
                y: p.fieldHeight
            }
            PathArc {
                x: p.deltaX
                y: p.fieldHeight
                radiusX: p.r
                radiusY: p.r
                direction: PathArc.Counterclockwise
            }
            PathLine {
                x: 0
                y: 0
            }
        }
    }
}
1 Answers

The problem is you're not specifying the start and end point of the line that the gradient should follow. Qt annoyingly has 2 different objects called LinearGradient and they have different property names. One is from QtGraphicalEffects, and the other is from QtQuick.Shapes. You're using the shapes version, so your gradient should look something like this:

fillGradient: LinearGradient {
    x1: 0
    y1: 0
    x2: p.fieldWidth
    y2: p.fieldHeight

    GradientStop {
        position: 0
        color: "#6c6c6c"
    }
    GradientStop {
        position: 1
        color: "#000000"
    }
}
Related