Qml: Adding content dynamically to a SequentialAni

2019-05-31 08:42发布

I have an Qml component with a SequentialAnimation containing a static sequence of PropertyAction components:

SequentialAnimation {
  id: anim
  running: true

  PropertyAction { target: icon; property: "iconid"; value: propStore.anim1 }
  PropertyAction { target: icon; property: "iconid"; value: propStore.anim2 }
  PropertyAction { target: icon; property: "iconid"; value: propStore.anim3 }
}

This accomplishes that a specific icon is animated. However now I'd like to make it a little bit dynamic by building the sequence dynamically. The reason is that the propStore isn't under my control, and users adding new images to the animation sequence require me to make changes to the Qml :(

How should I go about doing this?

My first thought was to dynamically add components to anim.animations, but that doesn't work (it seems to be a read-only property of SequentialAnimation.)

My next thought was to add a ListModel to the outer component, and in its Component.onCompleted slot I append objects of the shape { image: "animN" } (I get the "animN" strings using introspection on propStore.) Then I use the ListModel to populate a Repeater. However, the SequentialAnimation doesn't seem to accept a Repeater object.

标签: qt animation qml
1条回答
小情绪 Triste *
2楼-- · 2019-05-31 09:24

You can't append directly to anim.animations, but you can reaffect it to a new value. Build a JS array from anim.animation, append a dynamically created animation to it, then reaffect it to anim.animations.

Here's a simple example.

Component
{
    id: component
    SequentialAnimation
    {
        id: seq
        property string color
        PropertyAction {target: rect; property: "color"; value: seq.color}
        PauseAnimation { duration: 500 }
    }
}

function addAnim(color)
{
    var listAnim = []
    for(var i=0; i<anim.animations.length; i++)
        listAnim.push(anim.animations[i])
    var temp = component.createObject(root, {"color":color})
    listAnim.push(temp)
    anim.animations = listAnim
}

    Rectangle
{
    id: rect
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.top: parent.top
    anchors.bottom: row.top
    anchors.margins: 40
    border.width: 1

    SequentialAnimation
    {
        id: anim
    }
}

Row
{
    id: row
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 50
    anchors.horizontalCenter: parent.horizontalCenter
    spacing: 10

    Button {
        text: qsTr("Play")
        onClicked: anim.start()
    }
    Repeater
    {
        model: ["red", "green", "blue", "cyan", "magenta", "yellow"]

        Button {
            text: qsTr("Add %1").arg(modelData[0])
            onClicked: addAnim(modelData)
        }
    }
}
查看更多
登录 后发表回答