TopCat
TopCat

Reputation: 53

Godot - making labels on demand, and setting their font size with GDscript

Not to over explain, I basically need to create an unknown number of Labels, with unknown text. All fine and dandy - works. I can't seem to find how to change their font size though.

Here's what I have:

for string in string_list:
    var new_label = Label.new()
    new_label.text = string
    new_label.set("custom_fonts/font", load(FONTPATH))
    new_label.set("custom_fonts/settings/size", FONTSIZE)
    hbox.add_child(new_label)

The load font line I found on the QA forums, and extrapolated from that how to set up the set size line. They don't seem to work though and Godot isn't throwing any errors either. Doing this at runtime - if it makes any difference.

Searched the official docs, and QA. Fairly new to Godot so I might be looking in the wrong place.

Upvotes: 5

Views: 7875

Answers (2)

Chris
Chris

Reputation: 1106

As of Godot 4, you can update the font_size using:

var label = Label.new()
label.text = "plop"
label.set("theme_override_font_sizes/font_size", 80)

Upvotes: 1

rcorre
rcorre

Reputation: 7228

Given you are adding labels to an HBoxContainer, it looks like all you want to do is create a list of strings, which you could do with an ItemList. Items can be dynamically added using add_item. For a horizontal layout like an hbox, just set max_columns to 0:

A value of zero means unlimited columns, i.e. all items will be put in the same row.

Since your example uses the same font and size for all items, you just need to create a DynamicFont with the desired font and size, and assign this to the custom_font field of the ItemList. It is easiest to do this through the editor.

If for some reason you need to use individual Labels, just create a DynamicFont, make it part of a Theme, and assign this theme to a parent of the labels. Then all the labels will inherit this font.

Upvotes: 4

Related Questions