How do I get the size of a expanded label?

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

I’m trying to dynamically set text in a block and shape the block to fit the text. In order to do that I have set the label to Expand, with the idea that once the text was set I could use get_size() and adjust the block around the text to fit. However, size returns 0,0?

Here is my code:

get_node("Panel/Label").set_text(name)
var tsize = get_node("Panel/Label").get_size()
print("DEBUG: size=", tsize)

This just results in:

DEBUG: size=0,0

The label appears to show the text fine but I have not been able to figure out how to get the length in pixels of the end resulting label. Suggestions?

:bust_in_silhouette: Reply From: zombieCraig

I solved it myself. Not sure why get_size doesn’t work in this instance (it does when you create a label from scratch and use add_child. However, this method seems to work just fine:

get_node("Panel/Label").get_combined_minimum_size()
:bust_in_silhouette: Reply From: Daoist LastWish

I used a hacky way to get the size right. The issue here is that the Label widget will not immediately return the correct size after you have set the text. This is probably because the size calculations are deferred until the next _draw() call.

mLabelObj.set_text(" ")
mLabelObj.set_size(Vector2(8, 8))
mLabelObj.set_text(pText)
mLabelObj.set_size(Vector2(8, 8))
var aLabelSize = mLabelObj.get_size()
mLabelObj.set_size(aLabelSize)

The trick here is that when you set the widget size to a very small value, the widget will resize to a minimum size which still allows it to display all the contents. The first pair of calls

mLabelObj.set_text(" ")
mLabelObj.set_size(Vector2(8, 8))

Resize the label to minimum possible size. Then I set the text and resized the label to a small size again. This will result in a label with a minimum size that will still display the text.

mLabelObj.set_text(pText)
mLabelObj.set_size(Vector2(8, 8))
var aLabelSize = mLabelObj.get_size()

However, sometimes, after the _draw() call, the size of the Label is larger than aLabelSize. To avoid that, set the size of Label again.

mLabelObj.set_size(aLabelSize)

Now you have the size of the label in aLabelSize, and the label is also really of the same size. Hope that helps.