带有 PropertyAnimation 的 qt QML 可折叠嵌套 ListView

qt QML collapsible nested ListView with PropertyAnimation

我是 QT QML 的新手,我打算制作一个带有平滑动画的折叠列表视图。我看到了这个 https://gist.github.com/elpuri/3753756 代码。我尝试在折叠期间添加 PropertyAnimation 并扩展到代码。但是失败了,我应该如何让它工作?

我打算添加状态和翻译,但它不适用于两个不同的组件,

nestedModel.setProperty(index, "collapsed", !collapsed)
nestedModel.state = (collapsed.state === "COLLAPSED") ? "COLLAPSED" : "EXPANDED";

然后对于状态和转换,

delegate: Rectangle {
    id: rect_change
    color: "blue"
    //height: 200
    width: 300
    border.color: "black"
    border.width: 2
    state: "COLLAPSED"
    states: [
        State {
            name: "COLLAPSED"
            PropertyChanges { target: rect_change; height: 0; }
        },
        State {
            name: "EXPANDED"
            PropertyChanges { target: rect_change; height: 200; }
        }
    ]
    
    transitions: [
        Transition {
            from: "EXPANDED"
            to: "COLLAPSED"
            PropertyAnimation { property: "height"; duration: 400; }
        },
        Transition {
            from: "COLLAPSED"
            to: "EXPANDED"
            PropertyAnimation { property: "height"; duration: 400; }
        }
    ]
}

为了更简单的实现,去掉状态和转换,只在 height 上使用 Behavior。您可以更改链接到的示例中的 Loader,使其看起来像这样:

Loader {
    id: subItemLoader

    sourceComponent: subItemColumnDelegate
    onStatusChanged: if (status == Loader.Ready) item.model = subItems
    clip: true
    height: collapsed ? 0 : subItems.count * 40
    Behavior on height {
        NumberAnimation {
            duration: 400
        }
    }
}