如何在 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/