Skip to content

匹配元素

match 元素根据表达式(主体)的值,从一组分支中条件性地渲染元素。 当你需要在若干互斥状态之间进行选择时,它比一连串 if 元素更具可读性。

注意:match 是实验性的,可能会发生变化。 跟踪 issue:slint-ui/slint#1307。

match <match-subject> {
<case-value>: ElementType { /* ... */ }
<case-value>: ElementType { /* ... */ }
*: ElementType { /* ... */ } // optional wildcard, always last
}
slint

每个 <case-value> 都是一个字面量,会与 <match-subject> 进行比较。 当主体等于某个分支值时,就渲染该分支的元素。 如果存在通配分支 *,则在没有任何显式分支匹配时渲染它。

int 可以取的每个值无法一一列出,因此需要通配 * 分支。

export component StatusIndicator {
in property <int> status: 0;
match status {
-1: Rectangle { background: red; }
0: Rectangle { background: green; }
1: Rectangle { background: yellow; }
*: Rectangle { background: gray; }
}
}
slint

true 和 false 覆盖了 bool 可以取的每一个值,因此不需要通配符。

export component Toggle {
in-out property <bool> checked: false;
match checked {
true: Rectangle { background: blue; }
false: Rectangle { background: lightgray; }
}
}
slint

当主体的类型是已知枚举时,分支值可以直接使用枚举变体名,而无需用枚举名限定。 列出每个变体就能穷尽覆盖该枚举,因此不需要通配符。

enum Mode { View, Edit, Preview }
export component Editor {
in-out property <Mode> mode: View;
match mode {
View: Text { text: "Viewing"; }
Edit: TextInput { }
Preview: Rectangle { background: black; }
}
}
slint
export component Greeting {
in property <string> lang: "en";
match lang {
"en": Text { text: "Hello"; }
"sp": Text { text: "Hola"; }
"fr": Text { text: "Bonjour"; }
*: Text { text: "Hi"; }
}
}
slint

* 分支充当兜底分支,在没有任何显式分支匹配主体时渲染。 它必须作为最后一个分支出现,因此写在它之后的任何分支都永远无法到达,属于错误。

match answer {
42: Text { text: "Correct!"; }
*: Text { text: "Incorrect"; }
}
slint

match 必须处理其主体可以取的每一个值。

  • 对于 bool 和枚举主体,要么显式列出所有值,要么提供一个 * 分支。缺少某个值是错误(例如 Non-exhaustive match on bool: missing 'false')。
  • 对于所有其他类型(int、string、color、length……),值的集合是无限的,因此需要 * 分支。

字面量主体(例如 match 1 { … })会发出警告,因为总是应用同一个分支。

每个分支值都必须互不相同。已被更早分支覆盖的值是错误,包括转换后相等的值(例如 2 和 2.0,或 1s 和 1000ms)。

match count {
0: Rectangle { }
0: Rectangle { } // error: Duplicate case value
*: Rectangle { }
}
slint

任何求值为空元素 { } 的分支都不渲染任何内容。任何分支都可以为空,包括通配分支。

match show {
true: Text { text: "Hi"; }
false: { }
}
slint
match toggle {
0: Rectangle { background: white; }
1: Rectangle { background: black; }
*: { }
}
slint

match 元素功能尚处于早期阶段。以下限制适用:

  • match 必须至少包含一个分支。

  • 分支必须是字面量值。计算表达式、属性引用和函数调用不允许作为分支值。只接受普通字面量(整数、浮点数、布尔值、字符串、枚举变体、颜色、长度),可选择取负。

    // Property reference as a case value
    match value {
    some-property: Rectangle { } // error
    }
    // String concatenation as a case value
    match greeting {
    "hello " + "world": Text { } // error
    }
    slint
  • 浮点数比较会产生警告。对浮点值进行精确相等比较并不可靠,因此编译器会为每个带小数的浮点分支值发出警告。

  • @children 不能出现在 match 分支内部。

  • match 不能出现在全局组件或接口中。只有常规组件支持 match 元素。


© 2026 SixtyFPS GmbH