重复与数据模型
用 for-in 语法多次创建元素,模型中的每个条目创建一次:
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
模型可以是整数(重复那么多次)、数组, 或由你的业务逻辑提供的模型。 这就是构建列表和表格的方式:数据存放在模型中, 而 UI 声明单个条目长什么样:
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; } }}slint
与 for 相关的是 if 构造,它仅在条件成立时才实例化元素:
export component Example inherits Window { preferred-width: 50px; preferred-height: 50px; if area.pressed : foo := Rectangle { background: blue; } if !area.pressed : Rectangle { background: red; } area := TouchArea {}}slint
关于确切的语法,参见语言参考中的
重复与条件元素;
关于 length、索引、push、insert 和 remove 等数组操作,
参见数组与模型。
© 2026 SixtyFPS GmbH