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

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

相关推荐
C4程序员3 分钟前
Java百度身份证识别接口实现【配置即用】
java·开发语言
unityのkiven13 分钟前
C++中的虚表和虚表指针的原理和示例
开发语言·c++
炒空心菜菜17 分钟前
MapReduce 实现 WordCount
java·开发语言·ide·后端·spark·eclipse·mapreduce
(・Д・)ノ19 分钟前
python打卡day27
开发语言·python
芯眼42 分钟前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
愚润求学1 小时前
【Linux】动静态库链接原理
linux·运维·服务器·开发语言·笔记
呦呦彬1 小时前
【问题排查】easyexcel日志打印Empty row!
java·开发语言·log4j
Tummer83631 小时前
C#+WPF+prism+materialdesign创建工具主界面框架
开发语言·c#·wpf
九章云极AladdinEdu2 小时前
GPU与NPU异构计算任务划分算法研究:基于强化学习的Transformer负载均衡实践
java·开发语言·人工智能·深度学习·测试工具·负载均衡·transformer
好吃的肘子2 小时前
MongoDB 应用实战
大数据·开发语言·数据库·算法·mongodb·全文检索