12.29.2021 - Rust/GUI/Druid/Custom Widget

All posts

Posted On 12.29.2021

To create a custom widget in Druid, we create a new struct and implement Widget trait. Or create a function that returns an impl Widget.

Widget trait defined a few lifecycle methods for a Druid’s widget:

  • lifecycle: Called on every lifecycle events for a widget based on the framework’s state.
  • event: Called on every event sent to the widget (keyboard, mouse, window, custom events,…)
  • update: Used to update the widget’s internal state or when the application data changed.
  • paint: To draw the widget
  • layout: To re-calculate the layout of your widget

Example:

A custom widget as a function:

fn background_label() -> impl Widget<Color> {
    Label::dynamic(|color: &Color, _| {
        let (r, g, b, _) = color.as_rgba8();
        format!("#{:X}{:X}{:X}", r, g, b)
    })
    .background(make_color_swatch())
}

Or a full blown struct that implemented Widget trait:

struct FooWidget {
    internal_state_1: String;
    internal_state_2: bool;
}
 
impl Widget<AppData> for FooWidget {
    fn lifecycle(...) { }
    fn event(...) { }
    fn update(...) { }
    fn layout(...) { }
    fn paint(...) { }
}

Depends on how much control you want to have for your widget, choose one of the two types of implementation.