How can I set a label to change size according to the length of the text.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By stubbsy345
:warning: Old Version Published before Godot 3 was released.

So basically the player is being asked a question with multiple options. Some options may be one word, some may be many. So i need to set a maximum width to the label but have a variable height according to the length of text.

:bust_in_silhouette: Reply From: Zylann

I tried to fiddle with Label but I can’t find an option to resize it according to the text inside. If you know how many lines an option will have, you may be able to create labels dynamically in a script by offsetting them by label.get_line_length() * line_count, but if word wrapping is enabled I don’t see an option to get the number of wrapped lines. So you end up with a compromise with no word wrapping and manual line count for each option.

If you think the feature is missing you can eventually ask for it on Github, however even with it you would still have to do some layout scripting to get what you want.

I tried an alternative: putting labels in a VBoxContainer. It layouts them automatically fine, however word wrapping simply doesn’t work, it shrinks the label to an unreadable size :confused:

Edit: I just opened an issue about word wrapping behaviour Word wrap makes label unreadable when put in VBoxContainer · Issue #7679 · godotengine/godot · GitHub

:bust_in_silhouette: Reply From: One Lou

Well. It’s been a long time since you posted this but I just had the same problem and nobody seems to have solved it. Hope this helps.This is what I did and actually did the trick perfectly:

$Label.rect_size = $Label.get_font("font").get_string_size($Label.text)

I do this in a custom control node I made that uses a touch_screen_button that resizes along with the label and the control node it self anytime I change the text via script.

What this does is getting the string size (returns a vector2) based on a string using the font you got before using the “get_font()” method as character size refference. You can pass “font” as argument to the get_font() method to pass your current label font.

Thank you! That’s exactly what I was looking for :slight_smile:

hiulit | 2021-11-16 09:34

:bust_in_silhouette: Reply From: annemarietannengrund

it may be a bit late, but since this topic was found when i searched my issue.

these codesnippets helped my implement a solution for big or unknown length label content that i want wrapped inside a container.

https://github.com/annemarietannengrund/theGodotExperience/tree/main/Examples/Example1

i tried to give some example layouts, pointing out the key elements for the implementation and have it ready as a demoscene to try it out.

hf&gl :slight_smile: