Rust语言使用iced实现简单GUI页面

使用cargo新建一个rust项目

bash 复制代码
cargo new gui_demo
cd gui_demo

编辑Cargo.toml文件 ,添加iced依赖

rust 复制代码
[package]
name = "gui_demo"
version = "0.1.0"
edition = "2021"

[dependencies]
iced = "0.4.2"

编辑src/main.rs文件:

rust 复制代码
use iced::{button, widget::{Button, Column, Text}, Application, Command, Element, Settings, Subscription};
use iced::executor::Default as Executor;

// 定义应用程序的状态
struct RustGuiApp {
    count: i32,
    button_state: button::State,
}

// 定义应用程序的消息类型
#[derive(Debug, Clone, Copy)]
enum Message {
    IncrementPressed,
}

impl Application for RustGuiApp {
    type Executor = Executor;
    type Message = Message;
    type Flags = ();

    fn new(_flags: ()) -> (Self, Command<Self::Message>) {
        (
            RustGuiApp {
                count: 0,
                button_state: button::State::new(),
            },
            Command::none(),
        )
    }
    
    // 设置窗口标题
    fn title(&self) -> String {
        String::from("Rust GUI Example")
    }

    fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
        if let Message::IncrementPressed = message {
            self.count += 1;
        }
        Command::none()
    }

    fn view(&mut self) -> Element<Self::Message> {
        let button = Button::new(&mut self.button_state, Text::new("Increment"))
            .on_press(Message::IncrementPressed);

        //    添加文字和一些你想加的东西
        Column::new()
            .push(Text::new("Hello, Rust GUI!").size(50))
            .push(Text::new(self.count.to_string()).size(50))
            .push(button)
            .into()
    }

    fn subscription(&self) -> Subscription<Self::Message> {
        Subscription::none()
    }
}

fn main() -> iced::Result {
    RustGuiApp::run(Settings::default())
}

最后使用命令运行

bash 复制代码
cargo run

运行效果展示,还是挺不错滴

相关推荐
naruto_lnq2 小时前
分布式系统安全通信
开发语言·c++·算法
学嵌入式的小杨同学2 小时前
【Linux 封神之路】信号编程全解析:从信号基础到 MP3 播放器实战(含核心 API 与避坑指南)
java·linux·c语言·开发语言·vscode·vim·ux
Re.不晚3 小时前
Java入门17——异常
java·开发语言
精彩极了吧3 小时前
C语言基本语法-自定义类型:结构体&联合体&枚举
c语言·开发语言·枚举·结构体·内存对齐·位段·联合
南极星10054 小时前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言
baidu_247438614 小时前
Android ViewModel定时任务
android·开发语言·javascript
Dev7z4 小时前
基于 MATLAB 的铣削切削力建模与仿真
开发语言·matlab
不能隔夜的咖喱4 小时前
牛客网刷题(2)
java·开发语言·算法
小天源4 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
肉包_5115 小时前
两个数据库互锁,用全局变量互锁会偶发软件卡死
开发语言·数据库·c++