前言
最基本的分离数据与显示的方法是使用Repeater元素。它被用于实例化一组元素 项,并且很容易与一个用于填充用户界面的定位器相结合。 最基本的实现举例,repeater元素用于实现子元素的标号。每个子元素都拥有一个 可以访问的属性index,用于区分不同的子元素
基本用法
import QtQuick 2.14
import QtQuick.Controls 2.14
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Tabs")
Column
{
spacing: 5
anchors.centerIn: parent
Repeater
{
id:rep
// model:10
// model: ["11111","22222","33333","44444","555555","6666","777777"]
model: ListModel{
ListElement{name1: "heisai";value:"123456"}
}
Rectangle
{
id: yang
width: 640
height: 30
radius: 3
color: "lightBlue"
Text {
id: name
anchors.centerIn: parent
//text: qsTr("text:"+ index)
//text: qsTr("text:" + modelData)
text: qsTr("text:" + name1 + value)
}
MouseArea
{
anchors.fill: parent
onClicked:
{
console.log(name.text)
}
}
}
}
}
}
上面演示了三种用法:
1: model: 10 对应 text 只能获取到他的index 属性
2: model: [“11111”] 对应text 可以获取到 index, 以及modelData .
3: model: ListModel{
ListElement{name1: “heisai”;value:“123456”}
}
相对来说 比较自由,后面用来添加, 移除子元素
效果图data
添加 移除 元素
import QtQuick 2.14
import QtQuick.Controls 2.14
ApplicationWindow {
visible: true
width: 400
height: 600
title: qsTr("Tabs")
Column{
anchors.centerIn: parent
ListModel
{
id:my_model
ListElement{name: "q";}
}
Component
{
id: my_delegate
Rectangle
{
width: 40
height: 35
color: "red"
Text {
id:my_text
anchors.centerIn: parent
text:name
}
MouseArea
{
anchors.fill: parent
onClicked:
my_model.append({name: "q"}) // 添加一个元素
//my_model.remove(index) // 移除一个元素
}
}
}
Repeater
{
model: my_model
delegate:my_delegate
onItemAdded: console.log("add a item")
}
}
}