Getting text to expand

Godot Version

v4.3.stable.official [77dcf97d8]

Question

Is there a way to make text expand to fill a ui container the same way that a TextureRect expands?

For example, here’s a simple HBoxContainer with a TextureRect and a Label:

Both the TextureRect and the Label are configured to expand to fill the HBoxContainer.

If I resize the HBoxContainer, the TextureRect will resize to fill the container. The Label will also expand, but only the borders of the Label; the text itself stays the same size.

On a conceptual level, I understand that the expand setting is changing the borders of the Label, not the font size. The functionality I’m trying to achieve is so simple that I keep feeling like the answer must be something really obvious that I haven’t tried yet. I tried parenting the Label to a Node2d. When I did this, resizing the Node2d scaled the text in the way I wanted. But a Node2d doesn’t seem to work properly with ui containers.

Does anyone know what I’m missing here? Thanks!

Resizing the label won’t change its font size. You can try scaling (not sizing) the whole container.

You can write your own Container that changes the Label.font_size theme property whenever Container.sort_children is emitted. Something like:

@tool
extends Container


func _ready() -> void:
	# Whenever sort_children is emitted
	sort_children.connect(func():
		for child in get_children():
			# Find all the Label chidren
			if not child is Label:
				continue

			child = child as Label
			# Change their font_size
			child.add_theme_font_size_override("font_size", floor(size.y))
			# And fit them into the container
			fit_child_in_rect(child, Rect2(Vector2.ZERO, size))
	)


func _get_minimum_size() -> Vector2:
	# Get the minimum size of the container
	var min_x = 0
	# By getting all the Control children
	for child in get_children():
		if not child is Control:
			continue

		child = child as Control
		# And getting the maximum combined minimum size x value
		min_x = max(min_x, child.get_combined_minimum_size().x)

	return Vector2(min_x, 0)

It may not work for everything. Feel free to modify it as needed.

4 Likes

This seems to pretty much work perfectly. Thank you!