Skip to content

使用 global Name { /* .. 属性或回调 .. */ }声明一个全局单例,以使属性和回调在整个项目中可用。使用 Name.property访问它们。

例如,这对于一个公共调色板非常有用:

slint
global Palette { in-out property<color> primary: blue; in-out property<color> secondary: green;}
export component Example inherits Rectangle { background: Palette.primary; border-color: Palette.secondary; border-width:2px;}

导出全局对象以使其可从其他文件访问(请参阅模块)。要使你的全局对象对具有业务逻辑的原生代码可见,请从也导出主应用程序组件的文件重新导出一个全局对象。

slint
export global Logic { in-out property <int> the-value; pure callback magic-operation(int) -> int;}// ...
rust
slint::slint!{export global Logic { in-out property <int> the-value; pure callback magic-operation(int) -> int;}
export component App inherits Window { // ...}}
fn main() { let app = App::new(); app.global::<Logic>().on_magic_operation(|value| { eprintln!("magic operation input: {}", value); value *2 }); app.global::<Logic>().set_the_value(42); // ...}
C++
#include "app.h"
int main() { auto app = App::create(); app->global<Logic>().on_magic_operation([](int value) -> int { return value *2; }); app->global<Logic>().set_the_value(42); // ...}
js
let slint = require("slint-ui");let file = slint.loadFile("app.slint");let app = new file.App();app.Logic.magic_operation = (value) => { return value *2;};app.Logic.the_value =42;// ...
python
import slint
class App(slint.loader.app.App): @slint.callback(global_name="Logic")
 def magic_operation(self, value: int) -> int: return value *2
app = new App()app.Logic.the_value =42
# ...

注意

全局单例不在窗口之间共享。 这意味着你可能需要为在应用程序中创建的每个窗口实例初始化全局回调和属性。

可以使用双向绑定语法重新公开全局中的回调或属性。

slint
global Logic { in-out property <int> the-value; pure callback magic-operation(int) -> int;}
component SomeComponent inherits Text { //在任何组件中使用全局对象 text: "The magic value is:" + Logic.magic-operation(42);}
export component MainWindow inherits Window { //重新公开全局属性,以便原生代码可以访问或修改它们 in-out property the-value <=> Logic.the-value; pure callback magic-operation <=> Logic.magic-operation;
 SomeComponent {}}

基于 MIT 协议发布