+1 vote

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!

in Engine by (18 points)

3 Answers

+1 vote
Best answer

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)
by (289 points)
selected by

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

0 votes

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 getlineheight() and multiply it by label.getlinecount() RIGHT AFTER I set the text with label.text

p.s.: actually, in my case the getlineheight() 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.

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

by (63 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 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 webmaster@godotengine.org with your username.

Categories