rust 例子,-Rust Slint 分享一个项目完整工程 - Ok(0) =&gt

📅 2026-12-01 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 490 次阅读

Rust Slint 分享一个项目完整工程

一、源码分享1、效果展示2、源码分享2.1、工程搭建2.2、工程结构2.3、main.rs2.4、main.slint2.5、control.slint2.6、models.slint2.7、Cargo.toml2.8、源码资源下载

二、Slint详解1、核心特性2、架构模式 (MVU)3、优势4、适用场景5、总结

一、源码分享

1、效果展示

2、源码分享

2.1、工程搭建

参考我这篇博文:【Rust 使用Slint库开发UI界面工程搭建详细教程】

2.2、工程结构

2.3、main.rs

use std::{sync::{Arc, Mutex}, thread, time::Duration};

use slint::{PlatformError, ToSharedString,Timer};

slint::include_modules!();

use serialport::{self, SerialPort};

use chrono::{Local};

macro_rules! add_notification {

($models:expr,$type:expr,$message:expr,$timeout:expr) => {

$models.lock().unwrap().insert(0,notification_value{

mtype: $type,

message: $message,

timeout: $timeout,

});

};

}

fn main() ->Result<(), PlatformError>{

let app: MainWindow = MainWindow::new()?;

let weak: slint::Weak= app.as_weak();

let serial: Arc>>> = Arc::new(Mutex::new(None));let notification_models: Arc>> = Arc::new(Mutex::new(Vec::new()));let time_now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

println!("Time now: {}", time_now);

app.global::().on_btn_home_clicked({

let weak: slint::Weak= weak.clone();

let serial = serial.clone();

let notification_models = notification_models.clone();

move |id|{

if let Some(strong) = weak.upgrade(){

let _adapter: DataAdapter<'_>= strong.global::();

println!("Home button clicked:{}", id);

let value = format!("motor {} home\r\n",id);

let mut serial_guard = serial.lock().unwrap();

if let Some(port) = serial_guard.as_mut() {

let _ = port.write_all(value.as_bytes());

} else {

add_notification!(notification_models,notification_type::Warning,"串口未连接!".to_shared_string(), 2000);

}

}

}

});

app.global::().on_btn_write_clicked({

let weak: slint::Weak= weak.clone();

let serial = serial.clone();

let notification_models = notification_models.clone();

move |id,value|{

if let Some(strong) = weak.upgrade(){

let _adapter: DataAdapter<'_>= strong.global::();

println!("Home button clicked:{},{}", id,value);

if value.is_empty(){

add_notification!(notification_models,notification_type::Error,"参数为空!".to_shared_string(), 2000);

return;

}

let value = format!("motor {} run {}\r\n",id,value);

let mut serial_guard = serial.lock().unwrap();

if let Some(port) = serial_guard.as_mut() {

let _ = port.write_all(value.as_bytes());

} else {

add_notification!(notification_models,notification_type::Warning,"串口未连接!".to_shared_string(), 2000);

}

}

}

});

app.global::().on_btn_save_clicked({

let weak: slint::Weak= weak.clone();

let serial = serial.clone();

let notification_models = notification_models.clone();

move ||{

if let Some(strong) = weak.upgrade(){

let _adapter: DataAdapter<'_>= strong.global::();

println!("Save button clicked");

let mut serial_guard = serial.lock().unwrap();

if let Some(port) = serial_guard.as_mut() {

let _ = port.write_all("motor save\r\n".as_bytes());

add_notification!(notification_models,notification_type::Info,"执行参数保存!".to_shared_string(), 2000);

} else {

add_notification!(notification_models,notification_type::Warning,"串口未连接!".to_shared_string(), 2000);

}

}

}

});

app.global::().on_btn_refresh_clicked({

let weak: slint::Weak= weak.clone();

move ||{

if let Some(strong) = weak.upgrade(){

let adapter: DataAdapter<'_>= strong.global::();

println!("Refresh button clicked");

let ports = serialport::available_ports();

if let Ok(ports) = ports{

let port_names: Vec= ports

.into_iter()

.map(|port| slint::SharedString::from(port.port_name))

.collect();

adapter.set_avalible_ports(slint::ModelRc::new(slint::VecModel::from(port_names)));

}

}

}

});

app.global::().on_btn_connect_clicked({

let weak: slint::Weak= weak.clone();

let serial = serial.clone();

let notification_models = notification_models.clone();

move |value|{

if let Some(strong) = weak.upgrade(){

let adapter: DataAdapter<'_>= strong.global::();

let serial_val = serial.lock().unwrap().take();

if let Some(port) = serial_val{

// Close the existing port

let _ = std::mem::drop(port);

*serial.lock().unwrap() = None;

println!("Disconnected from port");

adapter.set_is_connect(false);

add_notification!(notification_models,notification_type::Error,format!("断开串口连接:{}",value).to_shared_string(), 2000);

return;

}

println!("Connect button clicked:{}", value);

let port_name = value.to_string();

match serialport::new(&port_name, 115200).open() {

Ok(port) => {

*serial.lock().unwrap() = Some(port);

println!("Successfully connected to {}", port_name);

adapter.set_is_connect(true);

add_notification!(notification_models,notification_type::Info,format!("连接串口成功:{}",value).to_shared_string(), 2000);

}

Err(e) => {

eprintln!("Failed to connect to {}: {}", port_name, e);

adapter.set_is_connect(false);

add_notification!(notification_models,notification_type::Error,format!("连接串口失败:{}",value).to_shared_string(), 2000);

}

}

}

}

});

//线程读取串口数据

thread::spawn({

let serial = serial.clone();

let notification_models = notification_models.clone();

move || {

loop{

{

let mut serial_guard = serial.lock().unwrap();

if let Some(port) = serial_guard.as_mut() {

let mut buffer = [0u8; 1024];

match port.read(&mut buffer){

Ok(0) => {

println!("No data received");

}

Ok(n) => {

let data = String::from_utf8_lossy(&buffer[..n]);

if data.ends_with("\r\n") {

println!("Received data: {}", data.trim_end_matches("\r\n"));

if data.contains("motor save success"){

add_notification!(notification_models,notification_type::Info,"参数保存成功!".to_shared_string(), 2000);

}

else if data.contains("motor save failed"){

add_notification!(notification_models,notification_type::Error,"参数保存失败!".to_shared_string(), 2000);

}

else{

let trim_data = data.trim_end_matches("\r\n");

let split: Vec<&str>= trim_data.split(" ").collect();

if split.len() == 4 {

let name = split[0];

let id = split[1].to_string().parse::().unwrap_or_default();

let fun = split[2];

let res = split[3].to_string();

if name == "motor" && fun == "home" {

if res.contains("success") {

add_notification!(notification_models,notification_type::Info,format!("电机{id}回零成功!").to_shared_string(), 2000);

}

else{

add_notification!(notification_models,notification_type::Error,format!("电机{id}回零失败!").to_shared_string(), 2000);

}

}

else if name == "motor" && fun == "run" {

if res.contains("success") {

add_notification!(notification_models,notification_type::Info,format!("电机{id}运行成功!").to_shared_string(), 2000);

}

else{

add_notification!(notification_models,notification_type::Error,format!("电机{id}运行失败!").to_shared_string(), 2000);

}

}

}

else{

add_notification!(notification_models,notification_type::Error,format!("串口数据格式错误!").to_shared_string(), 2000);

}

}

}

}

Err(e) => {

if e.kind() != std::io::ErrorKind::TimedOut {

eprintln!("Error reading from serial port: {}", e);

}

}

}

}

}

thread::sleep(Duration::from_millis(100));

}

}

});

//消息提示定时器处理

let timer = Timer::default();

timer.start(slint::TimerMode::Repeated, std::time::Duration::from_millis(100), {

let weak = weak.clone();

let notification_models = notification_models.clone();

move || {

if let Some(strong) = weak.upgrade(){

let adapter = strong.global::();

let mut to_remove = Vec::new();

{

let mut notification_models = notification_models.lock().unwrap();

for (index, item) in notification_models.iter_mut().enumerate() {

if item.timeout <= 0 {

to_remove.push(index);

} else {

item.timeout -= 100;

}

}

}

// 在锁外删除元素

if !to_remove.is_empty() {

let mut notification_models = notification_models.lock().unwrap();

for &index in to_remove.iter().rev() {

notification_models.remove(index);

}

}

let notifications = notification_models.lock().unwrap().clone();

adapter.set_notification_models(slint::ModelRc::new(slint::VecModel::from(notifications)));

}

}

});

let _ = app.run();

Ok(())

}

2.4、main.slint

import { AboutSlint, VerticalBox, LineEdit, HorizontalBox, Button, GroupBox, GridBox,

ComboBox, Spinner, Slider, ListView, Palette, ProgressIndicator, CheckBox, Switch } from "std-widgets.slint";

import { IconButton,IconComboBox } from "controls.slint";

import { DataAdapter,notification_type,notification_value} from "models.slint";

export { DataAdapter}

import "resources/Digitall.ttf";

import "resources/Yuanti.ttf";

component ItemView inherits Rectangle {

background: #000000;

border-width: 3px;

border-color: #ffffff;

border-radius: 20px;

in-out propertyid:0;

in propertyname:"未知名称";

in propertyicon:@image-url("resources/motor.svg");

in propertynormal:false;

out propertyvalue;

in propertystatus:"NORMAL";

callback btn_write_clicked();

callback btn_home_clicked();

Rectangle {

width: parent.width/3;

height: parent.height;

x:0;

VerticalBox {

padding-top: 15px;

padding-left: 10px;

Text {

text: "ID:"+id;

color:#ffffff;

font-size: 40px;

font-family: "01 Digitall";

}

Text {

height: 35px;

text: name;

color:#ffffff;

font-size: 15px;

wrap: char-wrap;

font-family: "ChillRoundF";

}

Image {

source:icon;

colorize:normal? #07f013:#ec5b2f;

}

}

}

Rectangle {

x:parent.width - self.width - 10px;

width: parent.width/3*2; 拼多多帮助力入口

height: parent.height - 20px;

background: #6d05e46f;

border-radius: 20px;

VerticalLayout {

padding: 10px;

HorizontalBox {

Text {

text: "输入位置:";

color: #ffffff;

vertical-alignment: center;

font-size: 15px;

font-family: "ChillRoundF";

}

LineEdit {

input-type: number;

edited(text) => {

value = text;

}

}

}

Rectangle {

Text {

text: status;

color: #ffffff;

font-family: "01 Digitall";

font-size: 30px;

}

}

HorizontalBox {

Button {

text: "启动归零";

clicked => {

btn_home_clicked();

}

}

Button {

text: "写入位置";

clicked => {

btn_write_clicked();

}

}

}

}

}

}

export component MainWindow inherits Window {

width: 850px;

height: 600px;

background: #6d05e4;

title: "湘潭无人机参数调试助手";

private propertyselect_port;

GridLayout {

width: parent.width;

height: parent.height;

spacing: 10px;

padding: 10px;

ItemView{

row: 0;

col: 0;

id: 1;

name: "飞机归中左上";

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

ItemView{

row: 0;

col: 1;

id: 2;

name: "飞机归中左下";

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

ItemView{

row: 1;

col: 0;

id: 3;

name: "飞机归中右上";

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

ItemView{

row: 1;

col: 1;

id: 4;

name: "飞机归中右下";

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

ItemView{

row: 2;

col: 0;

id: 5;

name: "平台升降";

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

ItemView{

row: 2;

col: 1;

id: 6;

btn_home_clicked => {

DataAdapter.btn_home_clicked(self.id);

}

btn_write_clicked => {

DataAdapter.btn_write_clicked(self.id, self.value);

}

}

HorizontalLayout {

height: 50px;

row: 3;

colspan: 0;

spacing: 10px;

btnConnect := IconButton {

width: self.height;

height: parent.height;

icon: DataAdapter.is_connect?@image-url("resources/connected.svg"):@image-url("resources/disconnect.svg");

normal_color:#654EFF;

hover_color:#3823f5;

pressed_color:#610633;

clicked => {

popupConnect.show();

}

}

IconButton {

width: self.height;

height: parent.height;

icon: @image-url("resources/save.svg");

normal_color:#654EFF;

hover_color:#3823f5;

pressed_color:#610633;

clicked => {

DataAdapter.btn_save_clicked();

}

}

HorizontalLayout {

spacing: 5px;

for item[index] in DataAdapter.notification_models:Rectangle{

background: #000000;

width: self.height*2;

height: parent.height ;

border-radius: 5px;

border-width: 1px;

border-color:item.mtype == notification_type.Info ? #00FF00 :item.mtype == notification_type.Warning? #eeff00: #f81f2a;

VerticalLayout {

padding: 4px;

Rectangle {

width: parent.width - parent.padding*2;

height: 4px;

background:item.mtype == notification_type.Info ? #00FF00 :item.mtype == notification_type.Warning? #eeff00: #f81f2a;

border-radius: self.height/2;

}

Text {

text: item.message;

color: #ffffff;

horizontal-alignment: center;

vertical-alignment: center;

font-size: 12px;

wrap: char-wrap;

font-family: "ChillRoundF";

}

}

}

}

}

}

popupConnect := PopupWindow {

x: 10px;

y: root.height - self.height - btnConnect.height - 15px;

width: 300px;

height: 200px;

close-policy:PopupClosePolicy.close-on-click-outside;

Rectangle {

background: #654EFF;

border-radius: 10px;

border-width: 2px;

border-color: white;

VerticalBox {

padding-left: 0px;

HorizontalBox {

width: popupConnect.width;

height: popupConnect.height/3;

padding-right: 15px;

padding-left: 15px;

spacing: 5px;

Rectangle {

combox_serial := IconComboBox {

model: DataAdapter.avalible_ports;

background_color: #DEFB3A;

border-width: 2px;

border-color: #fcfcfc;

border-radius: 10px;

text_color: #000000;

icon_source: @image-url("resources/serial.svg");

icon_color: #000000;

text_size: 18px;

enabled: !DataAdapter.is_connect;

current_text: root.select_port;

selected(index, text) => {

root.select_port = text;

}

}

}

IconButton {

width: self.height;

normal_color:#DEFB3A;

pressed_color:#76861c;

hover_color:#bdd62f;

icon_padding: 17px;

icon: @image-url("resources/refresh.svg");

icon_color: #000000;

enabled: !DataAdapter.is_connect;

clicked => {

DataAdapter.btn_refresh_clicked();

}

}

IconButton {

width: self.height;

normal_color:#DEFB3A;

pressed_color:#76861c;

hover_color:#bdd62f;

icon_padding: 15px;

icon: @image-url("resources/connect.svg");

icon_color: #000000;

clicked => {

DataAdapter.btn_connect_clicked(combox_serial.current_text);

}

}

}

Rectangle {

}

}

}

}

}

2.5、control.slint

import { ListView } from "std-widgets.slint";

export component IconButton {

in propertyicon <=> icon.source;

in propertyicon_padding:10px;

in propertyicon_color:#ffffff00;

in propertynormal_color:red;

in propertypressed_color:green;

in propertyhover_color:blue;

in propertydisabled_color:gray;

in propertyenabled:true;

callback clicked();

Rectangle {

width: parent.width;

height: parent.height;

background:enabled?(ta.pressed ?root.pressed_color:ta.has-hover?root.hover_color:root.normal_color):root.disabled_color;

border-radius: 10px;

border-width: 2px;

border-color: white;

animate background {

duration: 100ms;

}

ta := TouchArea {

clicked => {

if root.enabled {

clicked();

}

}

}

}

icon := Image {

z:10;

width: parent.width - icon_padding;

height: parent.height - icon_padding;

horizontal-alignment: center;

vertical-alignment: center;

colorize: icon_color;

}

}

export component IconComboBox inherits Rectangle {

in propertyicon_source <=> icon.source;

in propertyicon_color <=> icon.colorize;

in propertytext_size <=> text.font-size;

in propertytext_color :white;

in propertypopup_height : 150px;

in property <[string]> model;

callback selected(index:int,text:string);

in-out propertyenabled : true;

in-out propertycurrent_text;

in propertydisabled_color:gray;

in propertybackground_color: #DEFB3A;

private propertypopup_visible : false;

background: enabled?root.background_color:root.disabled_color;

animate background {

duration: 100ms;

}

HorizontalLayout {

padding-left: 5px;

spacing: 10px;

icon := Image {

y:(root.height - self.height)/2;

width: self.height;

height: root.height/1.4;

}

text := Text {

vertical-alignment: center;

color: root.text_color;

font-weight: 700;

text: root.current_text;

}

indictor := Text{

height: root.height;

width: self.height;

text: root.popup_visible ?"▼":"▲";

color: root.text_color;

font-size: root.text_size;

vertical-alignment: center;

horizontal-alignment: center;

}

}

ta := TouchArea{

clicked => {

if root.enabled {

root.popup_visible = !root.popup_visible;

pop.show();

}

}

}

pop := PopupWindow {

y: root.height+5px;

width: root.width;

height: root.popup_height - icon.height;

Rectangle {

background: root.background;

border-radius: 10px;

border-width: 1px;

border-color: #fbfbff;

ListView {

width: parent.width - 4px;

height: parent.height - 4px;

for item[idx] in root.model :Rectangle{

width: 100%;

height: 40px;

border-radius: 5px;

background: listTa.pressed ? root.background.darker(80%):listTa.has-hover?root.background.darker(40%):transparent;

VerticalLayout {

Text {

width: 100%;

height: 100%;

text: item;

vertical-alignment: center;

horizontal-alignment: center;

font-size: root.text_size;

color: root.text_color;

font-weight: 600;

}

/*Rectangle {

x:root.width/10;

width: root.width/1.3;

height: 2px;

background: gray;

}*/

}

listTa := TouchArea{

clicked => {

//text.text = item;

root.selected(idx,item);

root.popup_visible = false;

root.current_text = item;

pop.close();

}

}

}

}

}

close-policy: PopupClosePolicy.close-on-click-outside;

}

}

2.6、models.slint

export enum notification_type {

Info,

Warning,

Error

}

export struct notification_value {

mtype:notification_type,

message:string,

timeout:int,

}

export global DataAdapter {

in-out property <[string]> avalible_ports;

in-out propertyis_connect:false;

in-out property <[notification_value]> notification_models:[{mtype:notification_type.Error, message:"电机1运行成功!", timeout:2000}];

callback btn_home_clicked(int);

callback btn_write_clicked(int,string);

callback btn_save_clicked();

callback btn_connect_clicked(string);

callback btn_refresh_clicked();

}

2.7、Cargo.toml

[package]

name = "XiangtanUniversity"

version = "0.1.0"

edition = "2024"

[dependencies]

chrono = "0.4.42"

serialport = "4.8.1"

slint = "1.14.1"

[build-dependencies]

slint-build = "1.14.1"

2.8、源码资源下载

文章顶部下载。

二、Slint详解

Slint 是一个用于创建本地用户界面的声明式框架,特别为 Rust 设计,但也支持 C++。它的目标是提供一个轻量级、高效且易于使用的解决方案,用于构建具有现代外观和感觉的桌面和嵌入式应用程序的 UI。Slint 的核心思想是使用一种声明式的语言来描述用户界面,并将其与 Rust 的业务逻辑代码紧密结合。

1、核心特性

声明式 UI 语言 (.slint):

Slint 定义了自己的领域特定语言(DSL),通常写在 .slint 文件中。这种语言语法简洁,专注于描述 UI 的结构、布局、属性、状态和交互。示例 .slint 片段:import { Button } from "std-widgets.slint";

export component MainWindow {

width: 300px;

height: 200px;

VerticalLayout {

Button {

text: "Click Me!";

clicked => { // 处理点击事件的逻辑 }

}

Text {

text: "Hello Slint!";

}

}

}

响应式数据绑定:

Slint 支持声明式响应式编程模型。使用 := 运算符绑定属性值,当依赖项(如其他属性或状态变量)发生变化时,绑定会自动更新。例如:export component MainWindow {

in propertycount: 0; // 输入属性

out propertylabel_text: "Count: " + count; // 输出属性,绑定到 count

...

}

当 count 改变时,label_text 会自动更新。 状态管理:

使用 state 关键字定义组件的内部状态。状态变化会触发 UI 的重新渲染。例如:export component ToggleButton {

out propertychecked;

state propertyis_checked: false;

// 点击切换状态

clicked => {

is_checked = !is_checked;

checked = is_checked;

}

// UI 根据状态变化

background: is_checked ? @linear-gradient(...) : @solid-color(...);

...

}

与 Rust 集成:

使用 slint-build 或 slint-interpreter 库将 .slint 文件编译或解释成 Rust 代码。编译后,UI 组件在 Rust 中变成结构体,其属性、回调函数和函数都可以在 Rust 代码中访问和操作。在 Rust 中实例化和运行 UI 的典型代码:use slint::ComponentHandle;

slint::slint! { // 这里可以内联 .slint 代码,或使用路径指向文件

// ... .slint 内容 ...

}

fn main() {

let ui = MainWindow::new();

// 设置 Rust 回调

let ui_weak = ui.as_weak();

ui.on_button_clicked(move || {

let ui = ui_weak.unwrap();

// 处理点击事件,更新 UI 状态等

ui.set_some_property(new_value);

});

ui.run();

}

跨平台:

Slint 支持 Windows, macOS, Linux (X11/Wayland), 以及嵌入式平台(如通过 OpenGL ES 或软件渲染)。其渲染后端是可插拔的。 轻量级与高性能:

设计之初就考虑了资源受限的环境(如嵌入式设备)。渲染引擎高效,避免了不必要的重绘。生成的代码量相对较小。 内置组件库:

提供了一套基础组件(如 Button, Slider, TextInput, ListView 等),称为 “std-widgets”。用户可以基于这些基础组件构建自己的自定义组件。

2、架构模式 (MVU)

Slint 鼓励一种类似于 Model-View-Update (MVU) 或 Model-View-ViewModel (MVVM) 的模式:

View: 在 .slint 文件中声明式定义。Model/ViewModel/State: 在 .slint 文件中通过 property, state 和回调函数定义,或者在 Rust 中定义并通过绑定暴露给 UI。Update/Logic: 在 Rust 中实现,处理用户交互、业务逻辑,并更新 Model/State,进而通过绑定驱动 View 更新。

3、优势

开发效率: 声明式语法简化了 UI 构建和布局。.slint 文件清晰地将 UI 描述与逻辑分离。性能: 高效渲染和轻量级设计。跨平台: 一套代码支持多个目标平台。Rust 集成: 与 Rust 语言深度集成,利用 Rust 的安全性和性能。热重载 (部分支持): 在开发过程中,某些工具链支持修改 .slint 文件后无需重新编译整个 Rust 项目即可看到 UI 变化。

4、适用场景

桌面应用程序 (Windows, macOS, Linux)嵌入式设备 GUI需要轻量级、原生 UI 的 Rust 应用

5、总结

Slint 为 Rust 开发者提供了一个现代、声明式且高效的 UI 框架。它通过自定义的 .slint 语言描述界面,结合强大的响应式数据绑定和状态管理,并与 Rust 代码无缝集成。其轻量级和高性能的特点使其成为桌面和嵌入式应用 UI 开发的强有力候选方案。如果你正在寻找一个 Rust 生态下的原生 GUI 解决方案,Slint 绝对值得一试。

建议查阅 Slint 官方文档 和示例以获取更详细的信息和上手教程。

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧