Rust Druid 之 Flex 布局器使用

2021-05-24 10:36:56 浏览数 (1)

Flex 布局器

Cargo.toml:

dependencies

druid = { git = "https://github.com/linebender/druid.git", features="image", "png"}

Flex 内部有两种类型,一种是non-flex,其对应的函数为with_child,另外一种是flex类型,其对于的函数为with_flex child。

代码语言:txt复制
 -------non-flex----- -flex-----
|       child #1     | child #2 |


 ----flex------- ----flex-------
|    child #1   |    child #2   |

当使用with_child 添加元素时,flex会使用child的width,heigth。

当使用with_flex_child 添加元素时, flex会自动计算其长宽,一般与expand()结合使用。

例子:

布局一个等长宽的textbox

代码语言:txt复制
	===================
	=     textbox     =
	=				  =
	=				  =
	===================
	=     textbox     =
	=                 =
	=			      =
	===================
代码语言:txt复制
use druid::lens;
use druid::WidgetExt;
use druid::{
    widget::{Flex, TextBox},
    AppLauncher, Data, Size, Widget, WindowDesc,
};

#[derive(Data, Clone)]
pub struct DataText {
    pub data: String,
}

fn buid_root() -> impl Widget<DataText> {
    let s1 = lens!(DataText, data);
    let s2 = lens!(DataText, data);
    let text_box_up= TextBox::multiline().lens(s1);
    let text_box_down = TextBox::multiline().lens(s2);
    
    // 1.0 为比列参数
    Flex::column()
    .with_flex_child(text_box_up.expand(), 1.0)
    .with_flex_child(text_box_down.expand(), 1.0)

    // Flex::column().with_child(text_box_up).with_flex_child(text_box_down.expand(), 1.0)
}

fn main() {
    let m = DataText {
        data: "Hello".to_string(),
    };
    let w = WindowDesc::new(buid_root()).window_size(Size::new(400.0, 400.0));
    AppLauncher::with_window(w).log_to_console().launch(m).unwrap();
}

with_flex_chidwith_flex_chid

然后在右下角添加清空按钮, 注意这时同时用到了flex与non_flex。

代码语言:txt复制
fn buid_root() -> impl Widget<DataText> {
    let s1 = lens!(DataText, data);
    let s2 = lens!(DataText, data);
    let text_box_up= TextBox::multiline().lens(s1);
    let text_box_down = TextBox::multiline().lens(s2);

    let clear_btn = Button::new("Clear").on_click(|_ctx, data: &mut DataText, _env| data.data = "".to_string());

    Flex::column()
    .with_flex_child(text_box_up.expand(), 1.0)
    .with_flex_child(text_box_down.expand(), 1.0)
    .with_child(Flex::row().with_flex_child(SizedBox::empty().fix_height(20.0).expand_width(), 1.0).with_child(clear_btn))
}

with_flex_child   with_childwith_flex_child with_child

0 人点赞