1、对于用户,ListView是一个滚动区域,支持惯性滚动。(代理项delegates)
import QtQuick 2.0
Rectangle{
width: 80
height: 300
color: "white"
ListView{
anchors.fill: parent
anchors.margins: 20
clip:true
model:100
delegate: numberDelegate
spacing: 5
}
Component{
id:numberDelegate
Rectangle{
width: 40
height: 40
color: "lightGreen"
Text{
anchors.centerIn: parent
font.pixelSize: 10
text:index
}
}
}
}
Component只能包含一个顶层Item,而且在这个Item之外不能定义任何数据,除了id。 在顶层Item之内,则可以包含更多的子元素来协同工作,最终形成一个具有特定功能的组件。
Component通常用来给一个View提供图形化组件,比如ListVIew::delegate属性就需要一个Component来指定如何显示列表的每一个项,又比如ButtonStyle::background属性也需要一个Component来指定如何绘制Button的背景。
Component不是Item的派生类,而是从QQmlComponent继承而来的,虽然它通过自己的顶层Item为其他的view提供可视化组件,但它本身是不可见元素。你可以这么理解:你定义的组件是一个新的类型,他必须被实例化以后才能显示。而要实例化一个嵌入在QML文件中定义的Component,则可以通过Loader。
2、orientation(方向)
默认的链表视图只提供了一个垂直方向的滚动条,但是有时我们也需要水平方向的
ListView{
.
.
.
orientation:ListView.Horizontal
}
键盘导航和高亮
当使用基于触摸方式的链表视图时,默认提供的视图已经足够使用。在使用键盘甚至仅仅通过方向键选择一个元素的场景下,需要有标识当前选中元素的机制。在QML中,这被叫做高亮。
focus属性设置为true,它设置链表视图能够获得键盘焦点。
然后是highlight属性,指出使用的高亮代理元素。
import QtQuick 2.0
Rectangle{
width: 240
height: 300
color: "white"
ListView{
anchors.fill: parent
anchors.margins: 20
clip:true
model:100
// orientation: ListView.Horizontal
delegate: numberDelegate
spacing: 5
highlight: highlightComponent
focus: true
}
Component{
id:highlightComponent
Rectangle{
width: rect.width
color: "lightGreen"
}
}
Component{
id:numberDelegate
Item{
id:rect
width: 40
height: 40
// color: "lightGreen"
Text{
anchors.centerIn: parent
font.pixelSize: 10
text:index
}
}
}
}
添加动画效果
Component{
id:highlightComponent
// Rectangle{
// width: rect.width
// color: "lightGreen"
// }
Item {
width: ListView.view.width
height: ListView.view.currentItem.height
y: ListView.view.currentItem.y
Behavior on y {
SequentialAnimation {
PropertyAnimation { target: highlightRectangle; property: "opacity"; to: 0; duration: 200 }
NumberAnimation { duration: 1 }
PropertyAnimation { target: highlightRectangle; property: "opacity"; to: 1; duration: 200 }
}
}
Rectangle {
id: highlightRectangle
anchors.fill: parent
color: "lightGreen"
}
}
}
ListView与Component一般情况下需要配合使用