接口
interface 描述组件承诺履行的一份契约。
它列出了实现该接口的组件必须提供的属性、回调和函数。
这让你可以编写与任何实现了该接口的组件都能协作的代码,而无需关心具体类型。
注意:
interface和implement是实验性的,可能会发生变化。 跟踪 issue:slint-ui/slint#1870。
使用 interface 关键字,后跟列出该契约的主体。
interface TextInterface { in-out property <string> text;
public pure function length(text: string) -> int;}接口主体可以包含:
- 可见性为
in、out或in-out的属性。 不允许有默认值。 - 回调,可以是除
init之外的任何签名。 - 不带主体的函数声明。
它们必须是
public,并且可以是pure。
接口主体不能包含绑定、子元素、布局、states、双向绑定、animate 块或私有属性。
接口可以用 export interface 导出。
组件通过在其主体中写入 implement I <=> self; 语句来声明它实现了某个接口。
组件必须声明或继承接口中列出的每一个属性、回调和函数,并且要匹配
类型、可见性和纯性。如果某个成员缺失或与接口不匹配,编译器会将其报告为错误。
implement 语句的目标必须是 self 或某个子元素的 id(参见下面的委托),并且该语句
只允许直接写在组件的根元素中,不能写在嵌套的子元素中。root 和 parent 不是有效的
目标:由于 implement 只能用于根元素,在那里 root 和 self 指代同一个元素,因此请改用 self。
export component MyText { implement TextInterface <=> self;
in-out property <string> text <=> input.text;
input := TextInput { text: "Hello"; }
public pure function length(text: string) -> int { return text.character-count; }}组件可以将 implement 与 inherits 结合使用:
component MyText inherits Rectangle { implement TextInterface <=> self; // ...}一个组件可以实现多个接口,每个接口都通过自己的 implement 语句实现。多个 implement
语句暴露同名的属性、回调或函数是错误的。
用 implement <=> child 委托给子元素
Section titled “用 implement <=> child 委托给子元素”有时组件本身并不实现某个接口,但它包含的子元素实现了该接口。
implement I <=> child-id; 将子元素的接口暴露到父组件上,因此父组件的使用者看到的属性、回调和函数,就如同父组件直接实现了该接口一样。
component Container { implement TextInterface <=> inner; inner := MyText { }}指定的子元素必须满足所列接口的 API(直接满足,或通过它自己的委托满足)。
interface Counter { in-out property <int> value; callback increment();}
component CounterButton { // It is not necessary for CounterButton to `implement Counter <=> self;` // implement Counter <=> self;
in-out property <int> value; callback increment();
preferred-width: 100%; preferred-height: 100%;
increment => { value += 1; } TouchArea { clicked => { root.increment(); } }}
export component App { implement Counter <=> button;
button := CounterButton { } Text { text: "Count: \{button.value}"; }}App 通过 Counter 接口拥有一个 value 属性和一个 increment 回调,两者都由 button 提供。
© 2026 SixtyFPS GmbH