Search code examples
rustgtkgtk4

Button.set_hexpand(false) doesn't stop button from expanding


I am building a GUI Application using GTK4.8.3. I want two ScrolledWindows where one (containing a ListBox) can expand horizontally and the other (containing a Button) cannot. More precisely, I want to restrict the button's ability to hexpand.

From the GTK documentation, I am aware that Setting hexpand explicitly will override the automatic expand behavior.

When I use the following code snippet to create the widgets and attempt to restrict horizontal expansion, my button can still expand horizontally, along with its parent ScrolledWindow. Why is this and how can I fix it?

let hyphens_scrollbox = ListBox::builder()
    .width_request(windows::WIDTH)
    .hexpand(true)
    .build();

let hyphens_scrollwindow = ScrolledWindow::builder()
    .width_request(windows::WIDTH)
    .height_request(customising::SCROLL_HEIGHT)
    .hexpand(true)
    .vexpand(true)
    .hscrollbar_policy(PolicyType::Never)
    .vscrollbar_policy(PolicyType::Always)
    .child(&hyphens_scrollbox)
    .build();

let details_scrollwindow = ScrolledWindow::builder()
    .width_request(windows::WIDTH)
    .height_request(entries::CONTAINER_HEIGHT)
    .hscrollbar_policy(PolicyType::Never)
    .vscrollbar_policy(PolicyType::Automatic)
    .hexpand(false)
    .child(&details_scrollbox)
    .build();

let new_button = Button::builder()
    .label("Add new group")
    .margin_bottom(buttons::MARGIN)
    .hexpand(false)
    .build();

details_scrollwindow.append(&new_button);

let defaultsbox = GtkBox::builder()
    .orientation(Orientation::Vertical)
    .width_request(windows::WIDTH)
    .build();

defaultsbox.append(&hyphens_scrollwindow);
defaultsbox.append(&details_scrollwindow);

Solution

  • For some reason which is very confusing, there seems to be a relation between the "expand" properties and the gtk4::Align property which goes nearly undocumented.

    By setting this gtk4::Align property as well as the hexpand on the button only, I could get your case to work as you want it. For example:

    let new_button = Button::builder()
        .label("Add new group")
        .margin_bottom(buttons::MARGIN)
        .hexpand(false)
        .halign(Align::Start)
        .build();
    

    Visually:

    Not expanding

    Disclaimer: I don't know Rust and I have nothing here to test this code. Let me know if it does not work. I could only try it in C++.