rust编程UI框架-druid-lens练习使用

我们通过上几章的学习,我们做一个小练习,
效果图
效果图

实现一个效果,通过 按钮对滑块的操作,并且label显示滑块位置。
我们接下来开始实现这个小练习,我们使用的组件有 Button(按钮)、Slider(滑块)、Label(文本)、Flex(布局)。
让我们创建一个rust项目

cargo new lens_demo

让我们添加包

[dependencies]
druid = { git = "https://github.com/linebender/druid.git"}
添加我们需要用到的引用
use druid::widget::{Button,Label,Slider,Flex};
use druid::widget::Widget;
use druid::{Env, WindowDesc, AppLauncher, Data, Lens, WidgetExt};

创建我们的Data Lens

#[derive(Data,Clone,Lens)]
struct AppState{
    current:f64,
}

创建界面和启动程序

fn ui_builder() -> impl Widget<AppState> {

    //创建label显示滑块的位置数字 绑定了current
    let label = Label::new(|app_state:&AppState,_env:&Env|{ format!("{:.1}",app_state.current)});

    //创建滑块,with_range 设置滑块的开始位置结束位置,lens绑定了current,fix_width设置滑块的宽度
    let slider = Slider::new().with_range(1., 100.).lens(AppState::current).fix_width(250.);

    //创建减一按钮,fix_width 设置按钮的宽度,on_click 绑定点击事件,
    let button_reduce = Button::new("- 1").fix_width(100.).on_click(|_,app_state: &mut AppState,_|{
        //对值进行判断,不能小于1,修改current的值
        if app_state.current - 1. < 1. {
            app_state.current = 1.;
        }else{
            app_state.current -= 1.;
        }
    });

    let button_increase = Button::new("+ 1").fix_width(100.).on_click(|_,app_state: &mut AppState,_|{
        if app_state.current + 1. > 100. {
            app_state.current = 100.;
        }else{
            app_state.current += 1.;
        }
        
    });

    //创建布局垂直排列
    Flex::column()
        .with_child(
            //水平排列
            Flex::row()
            //添加显示位置的label
            .with_child(label)
        )
        .with_child(
            //水平排列
            Flex::row()
                //添加滑块
                .with_child(slider)   
        )
        .with_child(
            //水平排列
            Flex::row()
                //添加按钮
                .with_child(button_reduce)
                .with_child(button_increase).padding(10.)
        )
    

    

}

fn main() {
    let win = WindowDesc::new(ui_builder()).window_size((300.,200.)).title("rust语言编程");
    let _app = AppLauncher::with_window(win).launch(AppState{current:1.});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若梦网络编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值