如何在Qt QML中依次动画Repeater实例化的部分子项?
QML中实现Repeater子项依次延迟动画的标准组件方案
当然有标准组件可以实现,不用额外写Timer逻辑,Qt Quick的PauseAnimation配合动画组就能搞定,给你两种更简洁的实现方式:
方案一:代理内绑定索引延迟(推荐)
直接在Repeater的代理里,利用模型index计算每个子项的动画延迟,逻辑内聚在子项中:
import QtQuick 6.3 Item { width: 600; height: 400 Row { anchors.fill: parent spacing: 5 Repeater { id: _repeater model: 10 delegate: Rectangle { id: _rect width: 50; height: 50 color: "green" SequentialAnimation { id: _anim // 按索引设置延迟,每个子项比前一个晚150ms启动 PauseAnimation { duration: index * 150 } NumberAnimation { target: _rect; property: "height"; from: 50; to: 150; duration: 300 } NumberAnimation { target: _rect; property: "height"; from: 150; to: 50; duration: 300 } } } } } MouseArea { anchors.fill: parent onClicked: { // 启动所有子项动画,自动依次延迟 for (let i = 0; i < _repeater.count; i++) { _repeater.itemAt(i)._anim.start() } // 要是只想启动特定索引(比如1-4),改成下面这样: // [1,2,3,4].forEach(idx => _repeater.itemAt(idx)._anim.start()) } } }
方案二:统一动画组批量控制
如果需要统一管理所有子项的动画,用ParallelAnimation包裹带延迟的子动画,适合批量启停的场景:
import QtQuick 6.3 Item { width: 600; height: 400 Row { anchors.fill: parent spacing: 5 Repeater { id: _repeater model: 10 delegate: Rectangle { id: _rect width: 50; height: 50 color: "green" } } } ParallelAnimation { id: _batchAnim // 用Repeater给每个目标子项创建带延迟的动画 Repeater { // 这里可以直接指定要动画的索引,比如[1,2,3,4] model: 10 delegate: SequentialAnimation { PauseAnimation { duration: index * 150 } NumberAnimation { target: _repeater.itemAt(index); property: "height"; from:50; to:150; duration:300 } NumberAnimation { target: _repeater.itemAt(index); property: "height"; from:150; to:50; duration:300 } } } } MouseArea { anchors.fill: parent onClicked: { _batchAnim.start() } } }
对比你用Timer的方案,这两种都是Qt标准组件实现,不用手动维护索引队列,代码更简洁易读,动画逻辑和子项/动画组绑定,维护起来更方便。
内容的提问来源于stack exchange,提问作者senx
相关产品推荐
相关产品推荐

