Skip to content

组件容器

ComponentContainer 是一个内置元素,用于嵌入在运行时选择的组件。 要嵌入的组件由 Rust 代码以 ComponentFactory 的形式提供,并绑定到容器的 component-factory 属性。 这对于通过解释器动态加载 .slint 文件,或根据应用状态接入不同组件非常有用。

注意:ComponentContainer 是实验性的,可能会发生变化。 它目前只能从 Rust 使用。 跟踪 issue:slint-ui/slint#2390。

component-factorydefault: <???>

生成所嵌入组件的工厂。从 Rust 代码用 slint::ComponentFactory 为它赋值。更改此属性会替换所嵌入的组件。

booldefault: false

输出属性。当存在所嵌入的组件时设为 true, 否则为 false。可用于在未加载任何组件时显示占位内容。

该容器还具有通常的 width 和 height 属性。 所嵌入的组件被放置在容器内的 (0, 0) 处,其尺寸约束会传递到容器的布局信息中。

一个最小的 .slint 文件,将工厂暴露为根组件的一个属性:

export component MainWindow inherits Window {
in property <component-factory> plugin <=> container.component-factory;
VerticalLayout {
Text { text: container.has-component ? "Plugin loaded" : "No plugin"; }
container := ComponentContainer {
width: 300px;
height: 200px;
}
}
}
slint

Rust 侧创建一个 ComponentFactory,它在运行时用解释器编译一个 .slint 源,并将其设置到 plugin 属性上:

use slint::ComponentFactory;
use slint_interpreter::Compiler;
slint::include_modules!();
fn main() -> Result<(), slint::PlatformError> {
let main_window = MainWindow::new()?;
let factory = ComponentFactory::new(|ctx| {
let compiler = Compiler::new();
let result = spin_on::spin_on(compiler.build_from_source(
r#"
export component Plugin inherits Rectangle {
background: #3070ff;
Text { text: "Hello from plugin"; color: white; }
}
"#.into(),
Default::default(),
));
let definition = result.component("Plugin")?;
definition.create_embedded(ctx).ok()
});
main_window.set_plugin(factory);
main_window.run()
}
rust

传递给 ComponentFactory::new 的闭包会接收一个 FactoryContext,你应将其转发给 create_embedded。 只要容器需要,所嵌入的实例就会被重新构建。

静态编译的组件也可以嵌入:在闭包内调用 ComponentHandle::new() 并返回该句柄,而无需经过解释器。


© 2026 SixtyFPS GmbH