Search code examples
rustpadding

Iced add padding to only one side of a widget


I'm trying to work out how to add padding to only one side of a widget in iced it's fairly easy to add padding to either all sides or just the left/right or top/bottom e.g. the widget shown below has padding of 10 on it's left and right but no padding on the top/bottom.

let test = wgt::container("test")
    .style(wgt::container::rounded_box)
    .padding([0, 10]);          // todo: check how to add the padding only to the right

The documentation for iced's padding is here https://docs.iced.rs/iced/struct.Padding.html and https://docs.iced.rs/iced/padding/index.html they make it very clear that the crate individually implements padding for the, left right, top and bottom. However, I can't work out how to set the padding on each side only all sides or top/bottom and left/right.

How can I do each side individually.

P.S. for anyone wanting a minimal iced program for testing:

use iced;
use iced::widget as wgt;

#[derive(Default)]
struct State;

#[derive(Debug, Clone)]
enum Message {
    // ...
}

fn update(_state: &mut State, _message: Message) {}

fn view(_state: &State) -> iced::Element<'_, Message> {
    wgt::container("test")
        .style(wgt::container::rounded_box)
        .padding([0, 10])          // todo: check how to add the padding only to the right
        .into()
}

fn main() -> iced::Result {
    iced::run("test", update, view)
}

Solution

  • If you look into the documentation for the iced::padding namespace, you'll see that there are explicit functions for adding a Padding to the left, right, top and bottom sides only (as well as a function for adding a padding to all sides).

    Therefore this would be your minimal sample with a padding at the right side only:

    use iced;
    use iced::widget as wgt;
    
    #[derive(Default)]
    struct State;
    
    #[derive(Debug, Clone)]
    enum Message {
        // ...
    }
    
    fn update(_state: &mut State, _message: Message) {}
    
    fn view(_state: &State) -> iced::Element<'_, Message> {
        wgt::container("test")
            .style(wgt::container::rounded_box)
            .padding(iced::padding::right(10)) // Only add padding to the right side.
            .into()
    }
    
    fn main() -> iced::Result {
        iced::run("test", update, view)
    }
    

    Giving you this result:

    Sample program with right padding.