+2 votes

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?

in Engine by (58 points)

2 Answers

+2 votes
Best answer

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()
by (58 points)
edited by
0 votes

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.

by (14 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.