Label Resize Behavior

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

I’m trying to determine how I can get my label to update its size when a smaller string has been added to it. For example, I have a label that states “Sample Label” and its size comes out to (85, 14).

However, when I call the set_text method with a value of “A”, the label still reports a size of (85, 14). Is there a way to report the correct size with just the one character present?

Thanks in advance!

:bust_in_silhouette: Reply From: ingo_nikot

the label will not update size until its drawn:

example:

func _ready():
	print(self.get_size()) #100,14
	self.set_text("net text")
	print(self.get_size()) #STILL 100,14
	set_process(true)

func _process(delta):
	print(self.get_size()) #*NOW its 50,14
	set_process(false)

Thank you! That makes sense now. Still learning the ins and outs of Godot.

pcole | 2016-12-19 14:57

:bust_in_silhouette: Reply From: Larzans

GODOT 3.0:
in my case i needed to manually adapt the height of an outer container that contained a background NinePatchRect, so with just waiting for the _process I could catch the size change correctly, but then I had to change the size of the NinePatch, which took another drawcycle to be done and would not be shown immediately.

What DOES work actually right away is getting the number of lines after setting a new text for your label!

So in my specific case (ONLY vertical growth, now width change) I could just use get_line_height() and multiply it by label.get_line_count() RIGHT AFTER I set the text with label.text

p.s.: actually, in my case the get_line_height() did not give me the correct value, it reported the line to be 3 pixels lower than it actualy was, not sure if that has to do with some setting i used for my label, so i ended up using fixed line_height values in my script and adding a padding for good measure.

:bust_in_silhouette: Reply From: att2018
extends NinePatchRect
onready var label = get_node("Label")

func _ready():
	set_text("helloworldefsdfadfa")
	
func set_text(text):
	var n = len(text)
	if n <= 0:
		label.hide()
	else:
		text = " " + text + " "
		label.set_text(text)
		label.hide()
		label.show()

func _on_Label_item_rect_changed():
	if label == null:
		return
	var size = label.get_combined_minimum_size()
	rect_size = size
	margin_left = -size.x/2
	margin_right = size.x/2

hope to help

label.hide()
label.show()

This is a hands down ugly solution.
And it gets the job done in my specific scenario! Thank you!

mcsora | 2021-01-12 15:52