如何在 QML ScrollView 中为滚动设置动画? [英] How to animate scroll in a QML ScrollView?
问题描述
如何在 QML ScrollView 中设置滚动动画?
How can I animate scrolling in a QML ScrollView?
我已经在 contentItem.contentY
上尝试了一个 Behavior
,但这不起作用.
I've tried a Behavior
on the contentItem.contentY
, but that isn't working.
推荐答案
With Qt Quick Controls 1
您只需为属性 flickableItem.contentY
上的值更改设置动画.
With Qt Quick Controls 1
You just have to animate the value changes on the property 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 并平滑跳转.
When you click on the button, it will scroll by 100 px with a smooth jump.
flickableItem.contentY
不再可用.在 Qt Quick Controls 2 中做同样事情的最简单方法是为 ScrollBar
的位置设置动画.
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
.
请注意,QScrollBar
的位置是百分比(表示在 0 和 1 之间),而不是像素.
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)
}
}
当你点击按钮时,它会滚动 10% 的高度.
When you click on the button, it will scroll by 10% of the height.
这篇关于如何在 QML ScrollView 中为滚动设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!