Как анимировать прокрутку в QML ScrollView? - PullRequest
0 голосов
/ 20 июня 2019

Как анимировать прокрутку в QML ScrollView?

Я пробовал Behavior на contentItem.contentY, но это не работает.

1 Ответ

1 голос
/ 21 июня 2019

С Qt Quick Controls 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 пикселей.

С 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% высоты.

...