自由,分享
rust的gui框架-iced的计算器

网上的中文iced教程太少,拼凑了半天,终于能显示中文。
图片

use iced::{widget::{ Column, Text, Row, Button, text}, Sandbox, Length, Settings, Font, font::{Family, Weight}};

fn main() -> iced::Result{
    Counter::run(Settings {
        default_font: Font { //设置字体
            family: Family::Name("思源黑体 CN"),
            weight: Weight::Normal,
            ..Default::default()
        },
        ..Default::default() 
    })
}

#[derive()]
struct Counter{
    value:i32,
}

#[derive(Debug,Clone,Copy)]
enum Message {//枚举
    IncrementPressed,
    DecrementPressed,
}

impl Sandbox for Counter {
    type Message =Message;

    fn new() -> Self {
        Self { value: 0}
    }

    fn title(&self) -> String {//设置窗口标题
        String::from("pcb")
    }

    fn update(&mut self, message: Self::Message) {
        //逻辑更新
        match message {
            Message::IncrementPressed => {
                self.value += 1;
            }
            Message::DecrementPressed => {
                self.value -= 1;
            }
        }
    }

 
    fn view(&self) -> iced::Element<'_, Self::Message> {
        //定义小组件
        let anniujia =Button::new("+").on_press(Message::IncrementPressed).width(Length::Fill);
        let anniujian=Button::new("-").on_press(Message::DecrementPressed).width(Length::Fill);
        
        //组件布局
        Column::new().push(
            Text::new("pcb的计算器")
        ).push(
            Row::new().push(
                anniujia,
            ).push(
                text(self.value).size(22),
            ).push(anniujian,
        ))
        .align_items(iced::Alignment::Center).into()
    }
}