You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在QML中为HorizontalBarSeries实现BarSet数值动画?

QML中为HorizontalBarSeries的BarSet实现动画效果

你遇到的问题根源在于:BarSet的values是数组类型,而NumberAnimation仅能处理单个数值属性,直接对整个数组应用动画不会生效。下面提供两种可行的解决方案:

方案一:逐个元素手动添加动画

直接为values数组的每个索引创建独立的PropertyAnimation,针对单个数值进行动画:

ChartView {
    title: "Title of graphChart"
    anchors.fill: parent
    antialiasing: true
    legend.visible: false

    HorizontalBarSeries {
        id: _barSeries
        axisY: BarCategoryAxis {
            categories: ["Title1", "Title2", "Title3", "Title4", "Title5", "Title6", "Title7", "Title8"]
        }
        BarSet {
            id: barSet
            values: [0, 0, 0, 0, 0, 0, 0, 0]

            PropertyAnimation on values[0] { to: 1; duration: 600; running: true }
            PropertyAnimation on values[1] { to: 2; duration: 600; running: true }
            PropertyAnimation on values[2] { to: 3; duration: 600; running: true }
            PropertyAnimation on values[3] { to: 4; duration: 600; running: true }
            PropertyAnimation on values[4] { to: 5; duration: 600; running: true }
            PropertyAnimation on values[5] { to: 6; duration: 600; running: true }
            PropertyAnimation on values[6] { to: 7; duration: 600; running: true }
            PropertyAnimation on values[7] { to: 8; duration: 600; running: true }
        }
    }
}

方案二:动态生成动画(适合多元素场景)

如果BarSet的元素较多,手动写每个动画太繁琐,可以通过循环动态创建动画:

ChartView {
    title: "Title of graphChart"
    anchors.fill: parent
    antialiasing: true
    legend.visible: false

    HorizontalBarSeries {
        id: _barSeries
        axisY: BarCategoryAxis {
            categories: ["Title1", "Title2", "Title3", "Title4", "Title5", "Title6", "Title7", "Title8"]
        }
        BarSet {
            id: barSet
            values: [0, 0, 0, 0, 0, 0, 0, 0]
            // 定义目标数值数组
            property var targetValues: [1, 2, 3, 4, 5, 6, 7, 8]

            Component.onCompleted: {
                for (let i = 0; i < targetValues.length; i++) {
                    Qt.createQmlObject(`
                        PropertyAnimation {
                            target: barSet
                            property: "values[${i}]"
                            to: ${targetValues[i]}
                            duration: 600
                            running: true
                        }
                    `, barSet)
                }
            }
        }
    }
}

补充说明

PieSlice的value是单个数值属性,所以NumberAnimation可以直接生效;而BarSet的values是数组集合,必须针对每个元素单独做动画,ChartView才能捕捉到数值变化并更新条形的显示。

内容的提问来源于stack exchange,提问作者Erik Nikoyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:43:11