listview定义了一个要显示的数据模型和一个数据显示方式的委托。listview中的项是水平或垂直布局的。listview本质上是可flickable的,因为列表视图继承自flickable。
直接上代码:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 960
height: 720
title: qsTr("Hello World")
ListView {
id : listView
width: parent.width * 0.5
height: parent.height
anchors.margins: 20
clip: true
model: 100
delegate: numberDelegate
spacing: 5
focus: true
currentIndex: -1
property var lastCurrentIndex: -1
}
Component {
id: numberDelegate
Rectangle {
width: ListView.view.width
height: 40
border.color: Qt.lighter(color, 1.1)
color: listView.currentIndex == index ? "red" :"green"
Text {
anchors.centerIn: parent
font.pixelSize: 10
text: index
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onPressed: {
if (listView.lastCurrentIndex != -1) {
if(listView.itemAtIndex(listView.lastCurrentIndex)){
listView.itemAtIndex(listView.lastCurrentIndex).color = "green"
}
}
listView.currentIndex = index
color = "red"
listView.lastCurrentIndex = index
}
onEntered: {
if (listView.currentIndex == index) {
return
}
color = "blue"
}
onExited: {
if (listView.currentIndex == index) return
color = "green"
}
}
}
}
}
代码效果如下: