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

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

相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)3 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
Victoria.a5 小时前
数组和指针常见笔试题(深度剖析)
c语言·开发语言
..过云雨5 小时前
04.类和对象(下)(初始化列表、static静态成员、友元friend[类外函数使用类私有成员]、内部类、匿名对象等)
开发语言·c++