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

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

相关推荐
snow@li4 分钟前
d3.js:学习积累
开发语言·前端·javascript
编程岁月9 分钟前
java面试-0203-java集合并发修改异常、快速/安全失败原理、解决方法?
java·开发语言·面试
CoderCodingNo23 分钟前
【GESP】C++五级考试大纲知识点梳理, (3-4) 链表-双向循环链表
开发语言·c++·链表
llz_11232 分钟前
第五周作业(JavaScript)
开发语言·前端·javascript
W.Y.B.G1 小时前
JavaScript 计算闰年方法
开发语言·前端·javascript
jz_ddk1 小时前
[LVGL] 从0开始,学LVGL:基础构建篇 - 掌握UI的核心构建块
linux·网络协议·ui·rpc·嵌入式·gui·lvgl
liu****1 小时前
笔试强训(二)
开发语言·数据结构·c++·算法·哈希算法
无限进步_1 小时前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
qq_433554542 小时前
C++ 完全背包
开发语言·c++·算法
青铜弟弟2 小时前
R语言利用Export包导出pptx格式的文件有错误的原因
开发语言·r语言