根据官方文档,有三种方式可以使用slint库:
- The
.slintcode is inline in a macro.- The
.slintcode in external files compiled withbuild.rs- The
.slintcode is loaded dynamically at run-time from the file system, by using the interpreter API.
这里只介绍第二种,不推荐第一种将UI设计代码和程序逻辑耦合的方式,同时前两种方式因为在编译期转换slint代码,可以和IDE配合使用,提供代码提示。
在Cargo.toml中添加依赖和编译脚本
- 在
dependencies中新增 slint 库。 - 在
build-dependencies中引入 slint-build 库,它的功能是将 .slint 文件转换为 Rust 代码,并通过宏引入。 - 在
package中附加构建脚本,该程序将在主程序编译之前执行,负责将 slint 文件转换为 Rust 代码。
[package]
...
build = "build.rs"
edition = "2021"
[dependencies]
slint = "1.3.0"
...
[build-dependencies]
slint-build = "1.3.0"
编写Slint文件
编写一个名为 HelloWorld 的组件,该组件将以相同的名称引入到 Rust 代码中。在 Rust 中,可以实例化这个对象。
export component HelloWorld {
Text {
text: "hello world";
color: red;
}
}
创建编译脚本
在代码目录中创建编译脚本。如果与上述提供的 cargo.toml 文件一致,需要在项目根目录下创建一个 build.rs 文件。每次编译前,会先执行其中的内容。编译 slint 文件并生成相应的 Rust 代码:
fn main() {
// 传入你的slint文件地址
slint_build::compile("hello.slint").unwrap();
}
在程序中引入slint产生的代码
在程序开头使用slint::include_modules!()宏
slint::include_modules!();
fn main() {
HelloWorld::new().unwrap().run().unwrap();
}
实例化HelloWorld对象,调用run()方法,此时主进程会在这一行语句阻塞并显示UI,进入slint事件循环。