I’m trying to create a panel with a label to use as a callout in my game.
The nodes look like this:
PanelContainer->Label
Here’s what I would like to achieve:
When the text is longer than 200px, the label should auto-wraps and the panel shouldn’t be get than 200px (this I can achieve by setting the custom_minimum_size of the PanelContainer to 200)
When the text is shorter than 200px, the panel should shrink accordingly
I feel like I tried everything (both in the editor and through) code, but I just can’t get nr 2 to work.
Has anyone achieved something like this?
@tool
extends PanelContainer
@onready var label: Label = $Label
func _ready() -> void:
# set the label minimum width to 200px
label.custom_minimum_size.x = 200
# set autowrap
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
# set the size flags to begin to avoid the label being positioned incorrectly when changing the size
label.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
label.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
# When the label gets resized, change the size of this panel container to the minimum size of the label
label.resized.connect(func():
size = label.get_minimum_size()
)
// Get the size of the actual text
Vector2 textSize = Label.GetThemeDefaultFont().GetMultilineStringSize(
text, HorizontalAlignment.Center, MaxLabelWidth);
// Needed for the panel’s size to be able to be updated correctly
Label.Text = string.Empty;
// Update the label and the container to the size of the actual text
Size = Label.CustomMinimumSize = textSize;