# 基础模型
从模型中可视化数据的最基本方法是使用Repeater
(重复器)元素。 它用于实例化一组项目,并且很容易与定位器结合以填充用户界面的一部分。 重复器使用一个模型,该模型可以是任何内容,
可以是表示的实例化项目数量的数字,也可以是从网络上收集的成熟模型的数据。
# 使用数字
在其最简单的形式中,重复器可用于实例化指定数量的项。 每个项都可以访问一个附加属性——变量index
,它可用于区分项目。
在下面的示例中,重复器被用于创建一个项目的10个实例。 项的数量使用model
属性控制,它们的外观使用delegate
属性控制。 对于模型中的每一项,都会实例化一个代理(在这里,代理是一个BlueBox
,它是一个包含Text
元素的自定义Rectangle
)。text
属性设置为index
的值,因此项从0到9编号。
import QtQuick
import "../common"
Column {
spacing: 2
Repeater {
model: 10
delegate: BlueBox {
required property int index
width: 100
height: 32
text: index
}
}
}
# 使用数组
与编号项目列表相比,有时显示更复杂的数据集也很有趣。 通过用JavaScript数组替换整数的model
值,以实现这一点。 数组的内容可以是任何类型,可以是字符串、整数或对象。 在下面的示例中,使用了字符串列表。 这里仍然可以访问和使用index
变量,也可以访问包含数组中每个元素数据的modelData
。
import QtQuick
import "../common"
Column {
spacing: 2
Repeater {
model: ["Enterprise", "Columbia", "Challenger", "Discovery", "Endeavour", "Atlantis"]
delegate: BlueBox {
required property var modelData
required property int index
width: 100
height: 32
radius: 3
text: modelData + ' (' + index + ')'
}
}
}
# 使用ListModel
在了解了能够展示数组的数据后,很快就发现需要展示数组中每项包含的多个数据。在这里,模型开始有点意思了。ListModel
是最简单的模型之一,也是最常用的模型之一。 列表模型只是一组ListElement
项目的集合。 在每个列表元素内,有许多可以绑定到值的属性。 例如,在下面的示例中,为每个元素提供了名称和颜色。
每个元素内绑定的属性由重复器附加到每个实例化项。 这意味着变量name
和surfaceColor
可在由重复器创建的每个Rectangle
和Text
项的范围内使用。 这不仅可以轻松访问数据,还可以易于阅读源代码。 surfaceColor
是在名称左侧圆圈的颜色,而不是像使用来自j
行i
列的数据那样晦涩难懂。
import QtQuick
import "../common"
Column {
spacing: 2
Repeater {
model: ListModel {
ListElement { name: "Mercury"; surfaceColor: "gray" }
ListElement { name: "Venus"; surfaceColor: "yellow" }
ListElement { name: "Earth"; surfaceColor: "blue" }
ListElement { name: "Mars"; surfaceColor: "orange" }
ListElement { name: "Jupiter"; surfaceColor: "orange" }
ListElement { name: "Saturn"; surfaceColor: "yellow" }
ListElement { name: "Uranus"; surfaceColor: "lightBlue" }
ListElement { name: "Neptune"; surfaceColor: "lightBlue" }
}
delegate: BlueBox {
id: blueBox
required property string name
required property color surfaceColor
width: 120
height: 32
radius: 3
text: name
Box {
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
anchors.leftMargin: 4
width: 16
height: 16
radius: 8
color: blueBox.surfaceColor
}
}
}
}
# 将代理作为默认属性
Repeater
的delegate
属性是它的默认属性。 这意味着也可以将示例Example 01的代码编写如下:
import QtQuick
import "../common"
Column {
spacing: 2
Repeater {
model: 10
BlueBox {
required property int index
width: 100
height: 32
text: index
}
}
}