ListElement与ListModel
ListElement要定义在ListModel中,是模型列表中的元素,可以使用ListView或Repeater来访问。ListElement中的属性名是自定义的,首字母小写,属性值是个简单的常量。
ListModel是一个数据列表源,就像是ListElement的容器一样,封装了若干ListElement,元素个数可以通过count属性获得,附加属性index保存了当前元素在列表中的下标,还有一些可以动态改变这些属性的方法,如append()、insert()等,下面一一介绍。
1、一个简单的例子
import QtQuick 2.2
Rectangle {
id: home
width: 360; height: 360
color: "lightblue"
Component.onCompleted: {
console.log(fruitModel.count) // 3
}
ListModel {
id: fruitModel
ListElement {
name: "Apple"
colors: "red"
cost: 6.45
}
ListElement {
name: "Pear"
colors: "yellow"
cost: 4.25
}
ListElement {
name: "Grape"
colors: "purple"
cost: 5.15
}
}
Component {
id: fruitDelegate
Rectangle {
width: home.width; height: 20
color: colors
Row {
Text { width: 100; text: name }
Text { text: "$" + cost }
}
}
}
ListView {
anchors.fill: parent
model: fruitModel
delegate: fruitDelegate
}
}
运行结果:
上述例子中,ListModel包含了3个ListElement,属性名分别是“name”、“colors”、
“cost”,ListView的delegate将会访问model的数据。
2、ListElement可以有列表属性,给上述例子中的ListElement增加“attributes”列表属性,修改上述例子如下:
import QtQuick 2.2
Rectangle {
id: home
width: 360; height: 360
color: "lightblue"
Component.onCompleted: {
console.log(fruitModel.count) // 3
}
ListModel {
id: fruitModel
ListElement {
name: "Apple"
colors: "red"
cost: 6.45
attributes: [
ListElement { description: "Core" },
ListElement { description: "Deciduous" }
]
}
ListElement {
name: "Pear"
colors: "yellow"
cost: 4.25
attributes: [
ListElement { description: "Citrus" }
]
}
ListElement {
name: "Grape"
colors: "purple"
cost: 5.15
attributes: [
ListElement { description: "Tropical" },
ListElement { description: "Seedless" }
]
}
}
Component {
id: fruitDelegate
Rectangle {
width: home.width; height: 40
color: colors
Text { id: nameField; width: 100; text: name }
Text { text: '$' + cost; anchors.left: nameField.right }
Row {
anchors.top: nameField.bottom
spacing: 10
Text { text: "Attributes:" }
Repeater {
model: attributes
Text { text: description }
}
}
}
}
ListView {
anchors.fill: parent
model: fruitModel
delegate: fruitDelegate
}
}
运行结果:
例子中访问attributes列表属性用到了Repeater。
3、动态改变ListModel属性
先来看看ListModel有哪些方法:
append(jsobjectdict)
clear()
objectget(int index)
insert(intindex, jsobject dict)
move(intfrom, int to, int n)
remove(intindex, int count)
set(intindex, jsobject dict)
setProperty(intindex, string property, variant value)
sync()
这些方法的用法基本相同,在第一个例子中的fruitDelegate下添加一个MouseArea,动态插入一个元素,修改后的代码如下:
Component {
id: fruitDelegate
Rectangle {
width: home.width; height: 20
color: colors
Row {
Text { width: 100; text: name }
Text { text: "$" + cost }
}
MouseArea {
anchors.fill: parent
onClicked: {
fruitModel.insert(index, {"cost": 9.89, "colors": "orange", "name": "Orange"})
}
}
}
}
这样,点击某个元素后,就会在这个元素前插入对象{"cost":9.89, "colors": "orange", "name":"Orange"}并显示出来,例如点击Pear元素,结果如下:
其它方法用法类似。