Skip to content

具名插槽

slot 是一个具名插入点,组件在其中渲染由其使用者提供的内容。 它是对内置 @children 占位符的推广:组件不再只能有一个匿名的子元素块,而是可以声明多个插槽,并将每个插槽放置在自己布局中的不同位置。

注意:具名插槽是实验性的,可能会发生变化。 跟踪 issue:slint-ui/slint#6258。

在组件内使用 slot 关键字声明一个插槽,然后将插槽名称作为空元素写出,即可在所需位置渲染它。

export component Base inherits Rectangle {
slot header;
slot footer;
VerticalLayout {
header {} // render site for the `header` slot
@children // the default slot
footer {} // render site for the `footer` slot
}
}
slint

已声明的插槽必须且只能渲染一次。 @children 仍像以前一样工作,代表默认的、未命名的插槽。

组件的使用者用 << 运算符填充插槽,左侧写出插槽名称,右侧写出内容。 未赋值给具名插槽的内容照常进入 @children。

export component App inherits Rectangle {
Base {
header << Rectangle { background: blue; }
Text { text: "Main Content"; } // goes to @children
footer << Rectangle { background: gray; }
}
}
slint

插槽赋值是可选的。 未赋值的插槽不渲染任何内容。

绑定到插槽的名称是常规的元素引用,因此可以像读取任何其他元素一样读取它的属性。

export component App inherits Rectangle {
Base {
header << Rectangle { height: 8px; }
out property <length> header-y: header.absolute-position.y;
}
}
slint

组件可以通过 << 运算符将自己的某个插槽转发给子组件的插槽。 这让包装组件能够将嵌套组件的插槽作为自己的插槽暴露出来。

export component SlotHost inherits Rectangle {
slot host-header;
VerticalLayout {
host-header {}
@children
}
}
export component Outer inherits Rectangle {
slot header;
SlotHost {
host-header << header; // forward Outer's `header` into SlotHost's `host-header`
@children
}
}
slint
export component Card inherits Rectangle {
slot header;
slot footer;
VerticalLayout {
header {}
@children
footer {}
}
}
export component App inherits Window {
Card {
header << Text { text: "Title"; }
Text { text: "Body content"; }
footer << Text { text: "Footer"; }
}
}
slint

具名插槽功能尚处于早期阶段。以下限制适用:

  • 名称 children 保留给默认插槽。使用 @children 渲染它。

  • 已声明的插槽必须且只能渲染一次,并且不能放置在 for、if 或 match 元素内部。

  • 插槽不能放置在 PopupWindow 或 ComponentContainer 内部。

  • 插槽赋值和转发只对组件有效,并且每个插槽最多只能赋值一次。


© 2026 SixtyFPS GmbH