使用 for-in 语法来多次创建一个元素。
语法如下:for name[index] in model : id := Element { ... }
model 可以是以下类型:
- 一个整数,在这种情况下元素会重复该次数
- 原生声明的数组类型或模型,在这种情况下会为数组或模型中的每个元素实例化该元素。
name 将在元素内可用于查找,并将像一个伪属性一样被设置为模型的值。index 是可选的,将被设置为该元素在模型中的索引。 id 也是可选的。
示例
slint
export component Example inherits Window { preferred-width: 300px; preferred-height: 100px; for my-color[index] in [ #e11, #1a2, #23d ]: Rectangle { height: 100px; width: 60px; x: self.width * index; background: my-color; }}slint
export component Example inherits Window { preferred-width: 50px; preferred-height: 50px; in property <[{foo: string, col: color}]> model: [ {foo: "abc", col: #f00 }, {foo: "def", col: #00f }, ]; VerticalLayout { for data in root.model: my-repeated-text := Text { color: data.col; text: data.foo; } }}数组和模型
数组通过在数组元素类型两边加上 [ 和 ] 方括号来声明。
在 for 表达式中,数组字面量以及保存数组的属性充当模型。
slint
export component Example { in-out property<[int]> list-of-int: [1,2,3]; in-out property<[{a: int, b: string}]> list-of-structs: [{ a: 1, b: "hello" }, {a: 2, b: "world"}];}数组定义了以下操作:
array.length:可以使用内建的.length属性查询数组和模型的长度。array[index]:索引运算符检索数组中的各个元素。
越界访问数组将返回默认构造的值。
slint
export component Example { in-out property<[int]> list-of-int: [1,2,3];
out property <int> list-len: list-of-int.length; out property <int> first-int: list-of-int[0];}