函数与回调
Slint 为你提供了两种组织逻辑的方式:函数和回调。 两者都是带参数和返回值的可调用代码块——区别在于由谁来实现它们。 函数完全在 Slint 中定义。 回调的处理程序可以从 Rust、C++、JavaScript 或 Python 编写的业务逻辑中设置。 当原生代码需要作出反应时使用回调;否则使用函数。
用 function 关键字声明函数,并像其他语言那样调用它:
export component Example { property <string> my-property: my-function();
pure function my-function() -> string { return "result"; }}slint
默认情况下,函数是私有的。
把根级函数标记为 public,即可从其他组件——或从你的业务逻辑中调用它:
export component HasFunction { public pure function double(x: int) -> int { return x * 2; }}
export component CallsFunction { property <int> test: my-friend.double(1);
my-friend := HasFunction { }}slint
pure 关键字标记函数没有副作用,
这使它可以从属性绑定中调用;
参见纯度。
组件声明回调,以把状态变化传达给外部。
用 => 箭头语法声明处理程序来响应回调。
这里把内置 TouchArea 元素的 clicked 回调转发给一个自定义回调:
export component Example inherits Rectangle { // declare a callback callback hello;
area := TouchArea { // sets a handler with `=>` clicked => { // emit the callback root.hello() } }}slint
回调可以带参数和返回值:
export component Example inherits Rectangle { // declares a callback with a return value callback hello(int, int) -> int; hello(aa, bb) => { aa + bb }}slint
你还可以用双向绑定语法,通过别名把一个回调转发给另一个回调:
export component Example inherits Rectangle { callback clicked <=> area.clicked; area := TouchArea {}}slint
© 2026 SixtyFPS GmbH