Repeater 重复器
在QML(Qt Modeling Language)中,Repeater元素用于创建多个相同或相似的项。
它通常与ListView、GridView或其他容器一起使用,以便动态生成多个项。
以下是一个简单的示例,展示如何在QML中使用Repeater:
import QtQuick 2.15
import QtQuick.Controls 2.15
// 主应用程序窗口
ApplicationWindow {
visible: true // 设置窗口可见
width: 640 // 设置窗口宽度
height: 480 // 设置窗口高度
title: "Repeater Example" // 设置窗口标题
// 定义一个列表模型,包含水果名称
ListModel {
id: fruitModel // 模型的唯一标识
ListElement { name: "Apple" } // 列表元素,包含水果名称
ListElement { name: "Banana" }
ListElement { name: "Cherry" }
ListElement { name: "Date" }
}
// 定义一个ListView,用于显示水果列表
ListView {
anchors.fill: parent // 将ListView填充到父窗口
model: fruitModel // 设置ListView的数据模型为fruitModel
delegate: Rectangle { // 定义每个列表项的委托
width: parent.width // 设置矩形的宽度与父元素相同
height: 50 // 设置矩形的高度
color: "lightgray" // 设置矩形的背景颜色
border.color: "gray" // 设置矩形的边框颜色
border.width: 1 // 设置矩形的边框宽度
radius: 5 // 设置矩形的圆角半径
// 在矩形中显示水果名称
Text {
anchors.centerIn: parent // 将文本居中对齐在父矩形中
text: name // 设置文本内容为水果名称
font.pixelSize: 18 // 设置文本的字体大小
}
}
}
}
如果你希望直接使用Repeater而不依赖于ListView,可以这样做:
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Repeater Example"
Column {
anchors.centerIn: parent
spacing: 10
Repeater {
model: ["Apple", "Banana", "Cherry", "Date"]
delegate: Rectangle {
width: 100
height: 50
color: "lightgray"
border.color: "gray"
border.width: 1
radius: 5
Text {
anchors.centerIn: parent
text: modelData
font.pixelSize: 18
}
}
}
}
}