问题
How can I animate scrolling in a QML ScrollView?
I've tried a Behavior
on the contentItem.contentY
, but that isn't working.
回答1:
With Qt Quick Controls 1
You just have to animate the value changes on the property flickableItem.contentY
.
A quick example:
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"
}
}
}
}
}
}
When you click on the button, it will scroll by 100 px with a smooth jump.
With Qt Quick Controls 2
The flickableItem.contentY
isn't available anymore. The simpliest way to do the same thing in Qt Quick Controls 2 is to animate the position of the ScrollBar
.
Notice that the position of QScrollBar
is in percent (expressed between 0 and 1), not in pixels.
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)
}
}
When you click on the button, it will scroll by 10% of the height.
来源:https://stackoverflow.com/questions/56682077/how-to-animate-scroll-in-a-qml-scrollview