如何在渐变中动态添加停靠点

时间:2016-03-16 23:41:43

标签: qt qml qtquick2

我有以下渐变:

    Item {
        id: base
        width: 200
        height: 100
        start: Qt.point(0,0)
        end: Qt.point(width, 0)
        gradient: Gradient {
            GradientStop { position: 0.0; color: "white"}
            GradientStop { position: 0.5; color: "black" }
            GradientStop { position: 1.0; color: "white"}
        }

Gradient的停止属性没有任何成员函数可以追加新的停靠点,LinearGradient也没有。

如何添加停止以动态更改渐变?

另一种方法是在每次更改时创建一个新的LinearGradient。

1 个答案:

答案 0 :(得分:2)

Gradient被定义为list属性,如链接文档中所述,无法通过直接附加/删除元素来修改

Gradient添加新站点的唯一方法是重新分配stops属性list。以下是示例代码:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 200
    height: 100

    Rectangle {
        id: base
        anchors.fill: parent
        gradient: Gradient {
            id:gradient

            GradientStop { position: 0.0; color: "white"}
            GradientStop { position: 0.1; color: "black" }
            GradientStop { position: 0.3; color: "white"}
        }

        Component
        {
            id:stopComponent
            GradientStop {}
        }

        Component.onCompleted:
        {
            // Type 1: Aassign a all new stop list
            var s1 = stopComponent.createObject(base, {"position":0.2,"color":"red"});
            var s2 = stopComponent.createObject(base, {"position":0.4,"color":"yellow"});
            var s3 = stopComponent.createObject(base, {"position":0.6,"color":"blue"});
            gradient.stops = [s1,s2,s3];

            // Type 2:Append to the original stop list
            var newStops = [];
            for (var idx = 0; idx < gradient.stops.length;idx++)
            {
                newStops.push(gradient.stops[idx]);
            }
            newStops.push(s3);
            gradient.stops = newStops;
        }
    }
}