How do I get the text width of a RichTextLabel?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mjtorn

Hi!

It would appear this is a difficult one, judging by eg. RichTextLabel does not perform well 'out of the box' · Issue #10924 · godotengine/godot · GitHub

But the question is, is there any way to check the width of the text and resize the RichTextLabel accordingly? Or have it automatically resized to the text width without coding it manually through checking the width?

You can see how this is broken by adding a new stylebox (flat) to the label node. It defaults to a gray color and the background will always have the same size, regardless of what’s written into the label.

:bust_in_silhouette: Reply From: Diet Estus

RichTextLabel has a scroll_to_line() method, so there must be a way to access the number of lines.

If you could figure out how to get the number of lines, you could use code to slowly increase the width of the label (for example, by 1 pixel), until the number of lines is 1.

This isn’t ideal, of course, but it might serve as a viable workaround.

That’s a very interesting solution. Wonder if I would hide the RichTextLabel and it would adhere to this despite being hidden.

It is, as you say, not ideal. I will try it tomorrow regardless :slight_smile:

I would prefer it if we could find anyone who ever successfully adjusted a RichTextLabel without resorting to clever tricks or a Godot developer who can say why it’s so damned hard.

mjtorn | 2018-04-09 18:17

Now I’ve tried this.

Even when the text does not fit the label, get_visible_line_count() returns 1. This pretty much makes sense, there’s only one visible line.

So I didn’t even get to the point of adjusting its pixel width because it’s going to be one line anyway.

Then I realized there are cases for multi-line content, where you don’t even want the line to be only one line.

mjtorn | 2018-04-10 08:14

:bust_in_silhouette: Reply From: ketexon

One can get the font associated with the RichTextLabel using get_font("normal_font") (or whichever font you want) and use the get_string_size(String) function to get a Vector2 which contains the width and height of the string passed (RichTextLabel.text if you want to get the size of the current text).

Thanks! this has saved my text positioning system. Note that for multiline content, one needs to split lines and calculate each line individually.

jjmontes | 2020-10-14 09:16