qml - 如何在 QML ScrollView 中设置滚动动画?

标签 qml qtquick2

如何在 QML ScrollView 中设置滚动动画?

我已在 contentItem.contentY 上尝试了 Behavior,但不起作用。

最佳答案

使用 Qt 快速控件 1

您只需为属性 flickableItem.contentY 上的值更改设置动画即可。

一个简单的例子:

Item {
    anchors.fill: parent
    ColumnLayout {
        anchors.fill: parent
        Button {
            id: btn
            onClicked: scroll.scrollTo(scroll.flickableItem.contentY + 100)
        }

        ScrollView {
            id: scroll
            function scrollTo(y) {
                scrollAnimation.to = y
                scrollAnimation.start()
            }

            NumberAnimation on flickableItem.contentY {
                id: scrollAnimation
                duration: 1000
            }
            contentItem: Column {
                Repeater {
                        model: 30
                        Rectangle {
                            width: 100; height: 40
                            border.width: 1
                            color: "yellow"
                        }
                    }
            }
        }
    }
}

当您点击该按钮时,它将滚动 100 px,并平滑跳转。

使用 Qt Quick Controls 2

flickableItem.contentY 不再可用。在 Qt Quick Controls 2 中执行相同操作的最简单方法是为 ScrollBar 的位置设置动画。

请注意,QScrollBar 的位置以百分比为单位(在 0 到 1 之间表示),而不是以像素为单位。

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    ScrollView {
        id: scroll
        width: 200
        height: 200
        clip: true
        function scrollTo(y) {
            scrollAnimation.to = y
            scrollAnimation.start()
        }
        ScrollBar.vertical: ScrollBar {
            id: test
            parent: scroll
            x: scroll.mirrored ? 0 : scroll.width - width
            y: scroll.topPadding
            height: scroll.availableHeight
            active: scroll.ScrollBar.horizontal.active
            policy: ScrollBar.AlwaysOn

            NumberAnimation on position {
                id: scrollAnimation
                duration: 1000
            }
        }
        ListView {
            model: 20
            delegate: ItemDelegate {
                text: "Item " + index
            }
        }
    }
    Button {
        id: btn
        anchors.top: scroll.bottom
        onClicked: scroll.scrollTo(test.position + 0.1)
    }
}

当您点击该按钮时,它将滚动 10% 的高度。

关于qml - 如何在 QML ScrollView 中设置滚动动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56682077/

相关文章:

qt - 如何在未获得焦点的 QtQuick Item 中接收键盘事件?

python - QtQuick GeometryChanged 方法仅适用于加载组件的一个方向

c++ - 在 QQuickItem 引用上发出信号

c++ - 如何从 QQuickFramebufferObject 中访问关联的渲染器对象

c++ - 在 ImageView Blackberry 10 中动态设置 imageSource

c++ - QMetaObject::invokeMethod 无法调用 QML/JS 函数

qml - 滚动时隐藏 ListView 的突出显示

c++ - 将 TextStyle 从 C++ 传递到 QML

c++ - Qt5.2 Qml 支持 Ubuntu 全局菜单

qml - 何时使用 Qt Quick 2 中的哪些类以及如何使用?