一、写在前面
Rust我已经反复入门6年了,口罩之前2019年,我就买了那本《Rust编程之道》,中间反复拾起、放下,到今天还在入门阶段,为什么会这样的,主要是我关注的Rust在后端功能,比如数学物理仿真、科学计算、量化分析的可用性,觉得他在生态上与Python、Julia等差的还是比较多,所以在等它的生态。
二、想干的事情
用slint作为UI交互,搭建一个简单的UI,用rust实现简单逻辑,通过这个例子,在vs code中把slint与rust的开发环境建好。
点击按钮【点击我】,10秒钟后,按钮改变文字,变成【已点击】。
10秒后
三、环境配置
- 说明:
本文不做Rust开发环境安装的说明,因为是之前配置好的。
需要提示的一点就是,请用国内的镜像站来安装,,比如中科大的镜像站,不然容易卡死,详细操作请自行AI搜索。
1、为什么想用slint
我不想用QT,也不想学Web,我只想用rust来进行一些数据处理、科学计算。slint用rust开发,轻量级,我只想做几个按钮和简单参数的交互,Rust重点用来处理计算密集的阶段,数据可视化等阶段其实用python、julia和R更方便。
2、安装slint包
【扩展】--->【搜索slint】--->【install】
3、配置rust包的国内镜像地址
在【.cargo】目录下新增一个配置文件,config.toml,内容如下:
csharp
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
为什么要配置,因为在build的时候,会更新一些用到的包,如果用外网,会被卡死。
4、创建工作区的文件夹
创建一个项目文件夹
5、创建文件【源码】

(1)、slint文件
新的UI.slint
csharp
import { Button} from "std-widgets.slint";
component MainWindow {
in-out property <string> button_text: "点击我";
callback on_button_clicked();
width: 300px;
height: 200px;
VerticalLayout {
spacing: 20px;
alignment: center;
Text {
text: "Hello, Slint示例";
horizontal-alignment: center;
vertical-alignment: center;
}
Button {
text:root.button_text;
clicked => {
root.on_button_clicked();
}
}
}
}
vs code提供了可视化的预览按钮【Show Preview】
(2)、rust主逻辑文件
csharp
slint::include_modules!();
use std::rc::Rc;
use std::cell::RefCell;
use slint::Timer;
fn main() -> Result<(), slint::PlatformError> {
let ui = MainWindow::new()?;
let ui_weak = ui.as_weak();
// 创建一个计时器
let timer = Rc::new(RefCell::new(Timer::default()));
// 点击按钮后启动延时操作
ui.on_on_button_clicked({
let timer = timer.clone();
let ui_weak_outer = ui_weak.clone(); // 克隆一份用于外部闭包
move || {
let ui_weak_inner = ui_weak_outer.clone(); // 再克隆一份用于计时器闭包
timer.borrow_mut().start(
slint::TimerMode::SingleShot,
std::time::Duration::from_secs(10),
move || {
if let Some(ui) = ui_weak_inner.upgrade() {
ui.set_button_text("已点击".into());
}
},
);
}
});
ui.run()
}
(3)、build设置
csharp
fn main() {
slint_build::compile("src/新的UI.slint").unwrap();
}
(4)、Cargo配置
Cargo.toml
csharp
[package]
name = "slint_demo"
version = "0.1.0"
edition = "2021"
build = "build.rs"
[dependencies]
slint = "1.12.1"
[build-dependencies]
slint-build = "1.12.1"
四、编译、运行、发布
1、编译(Build)
命令:
csharp
cargo build

Build之前,会更新包的版本,如果不用镜像站,会一直卡住转圈圈
耗时40秒,还能接受。
2、运行(run)
命令:
csharp
cargo run


3、发布(release)
命令:
csharp
cargo build --release
运行结果: