一、目标效果
如下图所示,我们在 ListView 中添加100个子项,鼠标滚轮可以浏览上下,同时打印加载出的和已删除的项,方向键控制高亮块的显示位置。
二、具体代码
1. Main.qml
import QtQuick
Window {
title: "ListView 演示"
width: 80; height: 300
visible: true
ListView{
id: lv
anchors.fill: parent
anchors.margins: 20
clip: true //默认是 false,打开之后加载会更丝滑,没有忽然消失、忽然出现的突兀感
model: 100
delegate: Item{
id: wrapper
required property int index
width: lv.width; height: 40
Text {
anchors.centerIn: parent
text: wrapper.index
}
Component.onCompleted: {
console.log(index + " added.") //打印已添加的提示信息
}
Component.onDestruction: {
console.log(index + " deleted.") //打印已删除的提示信息
}
}
spacing: 5
cacheBuffer: 80 //该值为单个delegate的倍数,决定不可见区域的预绘制数量,可以节省一些内存,提高运行效率
highlight: highlightComponent //按键盘上的方向键可以控制移动的位置
focus: true //和高亮一起写,否则高亮项不会跟着移动
}
Component{
id: highlightComponent
GreyBox{
id: gb
width: lv.width
//增加一个切换时过渡的动画
y: lv.currentItem.y
Behavior on y{
SequentialAnimation{ //连续动画
PropertyAction {
target: gb; property: "opacity"; value: 0}
NumberAnimation{duration: 200}
PropertyAction {
target: gb; property: "opacity"; value: 1}
}
}
}
}
}
2. GreyBox.qml
import QtQuick
Rectangle{
color: "grey"
property alias text: label.text
radius: 8
Text {
id: label
text: ""
anchors.centerIn: parent
color: "white"
}
}