Can controls within box containers be sized to fit content automatically?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By voidshine

Godot seems to approach UI from the top down: parents manage their children. But very often it’s useful to let some layout information flow upward, from child to parent. The only way I see to do this currently is via rect_min_size – but it would be really nice to avoid having to measure and force min size via specialized script every time I want a control to use its natural size. Controls “know” how big they need to be, and they size themselves sensibly when not in box containers, but I see no way to indicate to the box container that the child should preserve its inherent size.

Here’s a simple example: I have an HBoxContainer with two buttons, Left and Right. I want Right to be just wide enough to contain its text, which can change at runtime. Then I want Left to expand to fill the remaining space. On left I set size_flags_horizontal to Fill and Expand, but it goes too far. Right gets squashed down to almost nothing, and I have to force its rect_min_size with script. I know I can set Right to expand with a ratio, but that is not what I’m looking for. Is it possible to have the button size itself according to its text as normal and then ask the parent box container to not force shrink it?

:bust_in_silhouette: Reply From: DDoop

I was able to get a pair of buttons inside an HBox to perform as you describe. Don’t modify the HBox’s size flags. Leave the smaller desired button with default size flag settings, and then give the larger one the ‘expand’ horizontal setting, as shown in this screenshot:

editor and inspector showing button control size flags

As you can see, the smaller button keeps the necessary size to fully display the text on the button, and the larger one takes up as much as it can (the hbox is set to 0.1, 0.1, 0.9, 0.9 anchors just to make it look nicer inside the panel)

Thank you for answering. You’re right, this is the default behavior that I expected to “just work” – and it does, by default.

I figured out what was causing my problem. I had “Clip Text” enabled on some of the buttons, and this changes the sizing behavior, making them collapse when another button expands.

voidshine | 2022-11-17 07:08