Class RichTextLabel
- Namespace
- Godot
- Assembly
- GodotSharp.dll
A control for displaying text that can contain custom fonts, images, and basic formatting. RichTextLabel manages these as an internal tag stack. It also adapts itself to given width/heights.
Note: Assignments to Text clear the tag stack and reconstruct it from the property's contents. Any edits made to Text will erase previous edits made from other manual sources such as AppendText(string) and the push_* / Pop() methods.
Note: RichTextLabel doesn't support entangled BBCode tags. For example, instead of using [b]bold[i]bold italic[/b]italic[/i], use [b]bold[i]bold italic[/i][/b][i]italic[/i].
Note:
push_*/pop_* functions won't affect BBCode.
Note: Unlike Label, RichTextLabel doesn't have a property to horizontally align text to the center. Instead, enable BbcodeEnabled and surround the text in a [center] tag as follows: [center]Example[/center]. There is currently no built-in way to vertically align text either, but this can be emulated by relying on anchors/containers and the FitContent property.
public class RichTextLabel : Control, IDisposable
- Inheritance
-
RichTextLabel
- Implements
- Inherited Members
Constructors
RichTextLabel()
public RichTextLabel()
Properties
AutowrapMode
If set to something other than Off, the text gets wrapped inside the node's bounding rectangle. To see how each mode behaves, see TextServer.AutowrapMode.
public TextServer.AutowrapMode AutowrapMode { get; set; }
Property Value
BbcodeEnabled
If true, the label uses BBCode formatting.
public bool BbcodeEnabled { get; set; }
Property Value
ContextMenuEnabled
If true, a right-click displays the context menu.
public bool ContextMenuEnabled { get; set; }
Property Value
CustomEffects
The currently installed custom effects. This is an array of RichTextEffects.
To add a custom effect, it's more convenient to use InstallEffect(Variant).
public Array CustomEffects { get; set; }
Property Value
DeselectOnFocusLossEnabled
If true, the selected text will be deselected when focus is lost.
public bool DeselectOnFocusLossEnabled { get; set; }
Property Value
DragAndDropSelectionEnabled
If true, allow drag and drop of selected text.
public bool DragAndDropSelectionEnabled { get; set; }
Property Value
FitContent
If true, the label's minimum size will be automatically updated to fit its content, matching the behavior of Label.
public bool FitContent { get; set; }
Property Value
HintUnderlined
If true, the label underlines hint tags such as [hint=description]{text}[/hint].
public bool HintUnderlined { get; set; }
Property Value
Language
Language code used for line-breaking and text shaping algorithms, if left empty current locale is used instead.
public string Language { get; set; }
Property Value
MetaUnderlined
If true, the label underlines meta tags such as [url]{text}[/url]. These tags can call a function when clicked if MetaClicked is connected to a function.
public bool MetaUnderlined { get; set; }
Property Value
ProgressBarDelay
The delay after which the loading progress bar is displayed, in milliseconds. Set to -1 to disable progress bar entirely.
Note: Progress bar is displayed only if Threaded is enabled.
public int ProgressBarDelay { get; set; }
Property Value
ScrollActive
If true, the scrollbar is visible. Setting this to false does not block scrolling completely. See ScrollToLine(int).
public bool ScrollActive { get; set; }
Property Value
ScrollFollowing
If true, the window scrolls down to display new content automatically.
public bool ScrollFollowing { get; set; }
Property Value
SelectionEnabled
If true, the label allows text selection.
public bool SelectionEnabled { get; set; }
Property Value
ShortcutKeysEnabled
If true, shortcut keys for context menu items are enabled, even if the context menu is disabled.
public bool ShortcutKeysEnabled { get; set; }
Property Value
StructuredTextBidiOverride
Set BiDi algorithm override for the structured text.
public TextServer.StructuredTextParser StructuredTextBidiOverride { get; set; }
Property Value
StructuredTextBidiOverrideOptions
Set additional options for BiDi override.
public Array StructuredTextBidiOverrideOptions { get; set; }
Property Value
TabSize
The number of spaces associated with a single tab length. Does not affect \t in text tags, only indent tags.
public int TabSize { get; set; }
Property Value
Text
The label's text in BBCode format. Is not representative of manual modifications to the internal tag stack. Erases changes made by other methods when edited.
Note: If BbcodeEnabled is true, it is unadvised to use the += operator with Text (e.g. text += "some string") as it replaces the whole text and can cause slowdowns. It will also erase all BBCode that was added to stack using push_* methods. Use AppendText(string) for adding text instead, unless you absolutely need to close a tag that was opened in an earlier method call.
public string Text { get; set; }
Property Value
TextDirection
Base text writing direction.
public Control.TextDirection TextDirection { get; set; }
Property Value
Threaded
If true, text processing is done in a background thread.
public bool Threaded { get; set; }
Property Value
VisibleCharacters
The number of characters to display. If set to -1, all characters are displayed. This can be useful when animating the text appearing in a dialog box.
Note: Setting this property updates VisibleRatio accordingly.
public int VisibleCharacters { get; set; }
Property Value
VisibleCharactersBehavior
Sets the clipping behavior when VisibleCharacters or VisibleRatio is set. See TextServer.VisibleCharactersBehavior for more info.
public TextServer.VisibleCharactersBehavior VisibleCharactersBehavior { get; set; }
Property Value
VisibleRatio
The fraction of characters to display, relative to the total number of characters (see GetTotalCharacterCount()). If set to 1.0, all characters are displayed. If set to 0.5, only half of the characters will be displayed. This can be useful when animating the text appearing in a dialog box.
Note: Setting this property updates VisibleCharacters accordingly.
public float VisibleRatio { get; set; }
Property Value
Methods
AddImage(Texture2D, int, int, Color?, InlineAlignment, Rect2?, Variant, bool, string, bool)
Adds an image's opening and closing tags to the tag stack, optionally providing a width and height to resize the image, a color to tint the image and a region to only use parts of the image.
If width or height is set to 0, the image size will be adjusted in order to keep the original aspect ratio.
If width and height are not set, but region is, the region's rect will be used.
key is an optional identifier, that can be used to modify the image via UpdateImage(Variant, ImageUpdateMask, Texture2D, int, int, Color?, InlineAlignment, Rect2?, bool, string, bool).
If pad is set, and the image is smaller than the size specified by width and height, the image padding is added to match the size instead of upscaling.
If sizeInPercent is set, width and height values are percentages of the control width instead of pixels.
public void AddImage(Texture2D image, int width = 0, int height = 0, Color? color = null, InlineAlignment inlineAlign = InlineAlignment.Center, Rect2? region = null, Variant key = default, bool pad = false, string tooltip = "", bool sizeInPercent = false)
Parameters
imageTexture2DwidthintheightintcolorColor?If the parameter is null, then the default value is
new Color(1, 1, 1, 1).inlineAlignInlineAlignmentregionRect2?If the parameter is null, then the default value is
new Rect2(new Vector2(0, 0), new Vector2(0, 0)).keyVariantpadbooltooltipstringsizeInPercentbool
AddText(string)
Adds raw non-BBCode-parsed text to the tag stack.
public void AddText(string text)
Parameters
textstring
AppendText(string)
Parses bbcode and adds tags to the tag stack as needed.
Note: Using this method, you can't close a tag that was opened in a previous AppendText(string) call. This is done to improve performance, especially when updating large RichTextLabels since rebuilding the whole BBCode every time would be slower. If you absolutely need to close a tag in a future method call, append the Text instead of using AppendText(string).
public void AppendText(string bbcode)
Parameters
bbcodestring
Clear()
Clears the tag stack.
Note: This method will not modify Text, but setting Text to an empty string also clears the stack.
public void Clear()
Deselect()
Clears the current selection.
public void Deselect()
GetCharacterLine(int)
Returns the line number of the character position provided. Line and character numbers are both zero-indexed.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetCharacterLine(int character)
Parameters
characterint
Returns
GetCharacterParagraph(int)
Returns the paragraph number of the character position provided. Paragraph and character numbers are both zero-indexed.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetCharacterParagraph(int character)
Parameters
characterint
Returns
GetContentHeight()
Returns the height of the content.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetContentHeight()
Returns
GetContentWidth()
Returns the width of the content.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetContentWidth()
Returns
GetLineCount()
Returns the total number of lines in the text. Wrapped text is counted as multiple lines.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetLineCount()
Returns
GetLineOffset(int)
Returns the vertical offset of the line found at the provided index.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public float GetLineOffset(int line)
Parameters
lineint
Returns
GetMenu()
Returns the PopupMenu of this RichTextLabel. By default, this menu is displayed when right-clicking on the RichTextLabel.
You can add custom menu items or remove standard ones. Make sure your IDs don't conflict with the standard ones (see RichTextLabel.MenuItems). For example:
public override void _Ready()
{
var menu = GetMenu();
// Remove "Select All" item.
menu.RemoveItem(RichTextLabel.MenuItems.SelectAll);
// Add custom items.
menu.AddSeparator();
menu.AddItem("Duplicate Text", RichTextLabel.MenuItems.Max + 1);
// Add event handler.
menu.IdPressed += OnItemPressed;
}
public void OnItemPressed(int id)
{
if (id == TextEdit.MenuItems.Max + 1)
{
AddText("\n" + GetParsedText());
}
}
Warning: This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their Visible property.
public PopupMenu GetMenu()
Returns
GetParagraphCount()
Returns the total number of paragraphs (newlines or p tags in the tag stack's text tags). Considers wrapped text as one paragraph.
public int GetParagraphCount()
Returns
GetParagraphOffset(int)
Returns the vertical offset of the paragraph found at the provided index.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public float GetParagraphOffset(int paragraph)
Parameters
paragraphint
Returns
GetParsedText()
Returns the text without BBCode mark-up.
public string GetParsedText()
Returns
GetSelectedText()
Returns the current selection text. Does not include BBCodes.
public string GetSelectedText()
Returns
GetSelectionFrom()
Returns the current selection first character index if a selection is active, -1 otherwise. Does not include BBCodes.
public int GetSelectionFrom()
Returns
GetSelectionTo()
Returns the current selection last character index if a selection is active, -1 otherwise. Does not include BBCodes.
public int GetSelectionTo()
Returns
GetTotalCharacterCount()
Returns the total number of characters from text tags. Does not include BBCodes.
public int GetTotalCharacterCount()
Returns
GetVScrollBar()
Returns the vertical scrollbar.
Warning: This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their Visible property.
public VScrollBar GetVScrollBar()
Returns
GetVisibleLineCount()
Returns the number of visible lines.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetVisibleLineCount()
Returns
GetVisibleParagraphCount()
Returns the number of visible paragraphs. A paragraph is considered visible if at least one of its lines is visible.
Note: If Threaded is enabled, this method returns a value for the loaded part of the document. Use IsReady() or Finished to determine whether document is fully loaded.
public int GetVisibleParagraphCount()
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected override bool HasGodotClassMethod(in godot_string_name method)
Parameters
methodgodot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected override bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signalgodot_string_nameName of the signal to check for.
Returns
InstallEffect(Variant)
Installs a custom effect. This can also be done in the RichTextLabel inspector using the CustomEffects property. effect should be a valid RichTextEffect.
Example RichTextEffect:
# effect.gd
class_name MyCustomEffect
extends RichTextEffect
var bbcode = "my_custom_effect"
...
Registering the above effect in RichTextLabel from script:
# rich_text_label.gd
extends RichTextLabel
func _ready():
install_effect(MyCustomEffect.new())
# Alternatively, if not using `class_name` in the script that extends RichTextEffect:
install_effect(preload("res://effect.gd").new())</code></pre>
public void InstallEffect(Variant effect)
Parameters
effectVariant
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected override bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
methodgodot_string_nameName of the method to invoke.
argsNativeVariantPtrArgsArguments to use with the invoked method.
retgodot_variantValue returned by the invoked method.
Returns
IsMenuVisible()
Returns whether the menu is visible. Use this instead of get_menu().visible to improve performance (so the creation of the menu is avoided).
public bool IsMenuVisible()
Returns
IsReady()
If Threaded is enabled, returns true if the background thread has finished text processing, otherwise always return true.
public bool IsReady()
Returns
MenuOption(int)
Executes a given action as defined in the RichTextLabel.MenuItems enum.
public void MenuOption(int option)
Parameters
optionint
Newline()
Adds a newline tag to the tag stack.
public void Newline()
ParseBbcode(string)
The assignment version of AppendText(string). Clears the tag stack and inserts the new content.
public void ParseBbcode(string bbcode)
Parameters
bbcodestring
ParseExpressionsForValues(string[])
Parses BBCode parameter expressions into a dictionary.
public Dictionary ParseExpressionsForValues(string[] expressions)
Parameters
expressionsstring[]
Returns
Pop()
Terminates the current tag. Use after push_* methods to close BBCodes manually. Does not need to follow add_* methods.
public void Pop()
PopAll()
Terminates all tags opened by push_* methods.
public void PopAll()
PopContext()
Terminates tags opened after the last PushContext() call (including context marker), or all tags if there's no context marker on the stack.
public void PopContext()
PushBgcolor(Color)
Adds a [bgcolor] tag to the tag stack.
public void PushBgcolor(Color bgcolor)
Parameters
bgcolorColor
PushBold()
Adds a [font] tag with a bold font to the tag stack. This is the same as adding a [b] tag if not currently in a [i] tag.
public void PushBold()
PushBoldItalics()
Adds a [font] tag with a bold italics font to the tag stack.
public void PushBoldItalics()
PushCell()
Adds a [cell] tag to the tag stack. Must be inside a [table] tag. See PushTable(int, InlineAlignment, int) for details.
public void PushCell()
PushColor(Color)
Adds a [color] tag to the tag stack.
public void PushColor(Color color)
Parameters
colorColor
PushContext()
Adds a context marker to the tag stack. See PopContext().
public void PushContext()
PushCustomfx(RichTextEffect, Dictionary)
Adds a custom effect tag to the tag stack. The effect does not need to be in CustomEffects. The environment is directly passed to the effect.
public void PushCustomfx(RichTextEffect effect, Dictionary env)
Parameters
effectRichTextEffectenvDictionary
PushDropcap(string, Font, int, Rect2?, Color?, int, Color?)
Adds a [dropcap] tag to the tag stack. Drop cap (dropped capital) is a decorative element at the beginning of a paragraph that is larger than the rest of the text.
public void PushDropcap(string @string, Font font, int size, Rect2? dropcapMargins = null, Color? color = null, int outlineSize = 0, Color? outlineColor = null)
Parameters
stringstringfontFontsizeintdropcapMarginsRect2?If the parameter is null, then the default value is
new Rect2(new Vector2(0, 0), new Vector2(0, 0)).colorColor?If the parameter is null, then the default value is
new Color(1, 1, 1, 1).outlineSizeintoutlineColorColor?If the parameter is null, then the default value is
new Color(0, 0, 0, 0).
PushFgcolor(Color)
Adds a [fgcolor] tag to the tag stack.
public void PushFgcolor(Color fgcolor)
Parameters
fgcolorColor
PushFont(Font, int)
Adds a [font] tag to the tag stack. Overrides default fonts for its duration.
Passing 0 to fontSize will use the existing default font size.
public void PushFont(Font font, int fontSize = 0)
Parameters
PushFontSize(int)
Adds a [font_size] tag to the tag stack. Overrides default font size for its duration.
public void PushFontSize(int fontSize)
Parameters
fontSizeint
PushHint(string)
Adds a [hint] tag to the tag stack. Same as BBCode [hint=something]{text}[/hint].
public void PushHint(string description)
Parameters
descriptionstring
PushIndent(int)
Adds an [indent] tag to the tag stack. Multiplies level by current TabSize to determine new margin length.
public void PushIndent(int level)
Parameters
levelint
PushItalics()
Adds a [font] tag with an italics font to the tag stack. This is the same as adding an [i] tag if not currently in a [b] tag.
public void PushItalics()
PushLanguage(string)
Adds language code used for text shaping algorithm and Open-Type font features.
public void PushLanguage(string language)
Parameters
languagestring
PushList(int, ListType, bool, string)
Adds [ol] or [ul] tag to the tag stack. Multiplies level by current TabSize to determine new margin length.
public void PushList(int level, RichTextLabel.ListType type, bool capitalize, string bullet = "•")
Parameters
levelinttypeRichTextLabel.ListTypecapitalizeboolbulletstring
PushMeta(Variant)
Adds a meta tag to the tag stack. Similar to the BBCode [url=something]{text}[/url], but supports non-string metadata types.
Note: Meta tags do nothing by default when clicked. To assign behavior when clicked, connect MetaClicked to a function that is called when the meta tag is clicked.
public void PushMeta(Variant data)
Parameters
dataVariant
PushMono()
Adds a [font] tag with a monospace font to the tag stack.
public void PushMono()
PushNormal()
Adds a [font] tag with a normal font to the tag stack.
public void PushNormal()
PushOutlineColor(Color)
Adds a [outline_color] tag to the tag stack. Adds text outline for its duration.
public void PushOutlineColor(Color color)
Parameters
colorColor
PushOutlineSize(int)
Adds a [outline_size] tag to the tag stack. Overrides default text outline size for its duration.
public void PushOutlineSize(int outlineSize)
Parameters
outlineSizeint
PushParagraph(HorizontalAlignment, TextDirection, string, StructuredTextParser, JustificationFlag, float[])
Adds a [p] tag to the tag stack.
public void PushParagraph(HorizontalAlignment alignment, Control.TextDirection baseDirection = TextDirection.Auto, string language = "", TextServer.StructuredTextParser stParser = StructuredTextParser.Default, TextServer.JustificationFlag justificationFlags = JustificationFlag.Kashida | JustificationFlag.WordBound | JustificationFlag.SkipLastLine | JustificationFlag.DoNotSkipSingleLine, float[] tabStops = null)
Parameters
alignmentHorizontalAlignmentbaseDirectionControl.TextDirectionlanguagestringstParserTextServer.StructuredTextParserjustificationFlagsTextServer.JustificationFlagtabStopsfloat[]If the parameter is null, then the default value is
Array.Empty<float>().
PushStrikethrough()
Adds a [s] tag to the tag stack.
public void PushStrikethrough()
PushTable(int, InlineAlignment, int)
Adds a [table=columns,inline_align] tag to the tag stack.
public void PushTable(int columns, InlineAlignment inlineAlign = InlineAlignment.ToTop, int alignToRow = -1)
Parameters
columnsintinlineAlignInlineAlignmentalignToRowint
PushUnderline()
Adds a [u] tag to the tag stack.
public void PushUnderline()
RemoveParagraph(int)
Removes a paragraph of content from the label. Returns true if the paragraph exists.
The paragraph argument is the index of the paragraph to remove, it can take values in the interval [0, get_paragraph_count() - 1].
public bool RemoveParagraph(int paragraph)
Parameters
paragraphint
Returns
ScrollToLine(int)
Scrolls the window's top line to match line.
public void ScrollToLine(int line)
Parameters
lineint
ScrollToParagraph(int)
Scrolls the window's top line to match first line of the paragraph.
public void ScrollToParagraph(int paragraph)
Parameters
paragraphint
ScrollToSelection()
Scrolls to the beginning of the current selection.
public void ScrollToSelection()
SelectAll()
Select all the text.
If SelectionEnabled is false, no selection will occur.
public void SelectAll()
SetCellBorderColor(Color)
Sets color of a table cell border.
public void SetCellBorderColor(Color color)
Parameters
colorColor
SetCellPadding(Rect2)
Sets inner padding of a table cell.
public void SetCellPadding(Rect2 padding)
Parameters
paddingRect2
SetCellRowBackgroundColor(Color, Color)
Sets color of a table cell. Separate colors for alternating rows can be specified.
public void SetCellRowBackgroundColor(Color oddRowBg, Color evenRowBg)
Parameters
SetCellSizeOverride(Vector2, Vector2)
Sets minimum and maximum size overrides for a table cell.
public void SetCellSizeOverride(Vector2 minSize, Vector2 maxSize)
Parameters
SetTableColumnExpand(int, bool, int)
Edits the selected column's expansion options. If expand is true, the column expands in proportion to its expansion ratio versus the other columns' ratios.
For example, 2 columns with ratios 3 and 4 plus 70 pixels in available width would expand 30 and 40 pixels, respectively.
If expand is false, the column will not contribute to the total ratio.
public void SetTableColumnExpand(int column, bool expand, int ratio = 1)
Parameters
UpdateImage(Variant, ImageUpdateMask, Texture2D, int, int, Color?, InlineAlignment, Rect2?, bool, string, bool)
Updates the existing images with the key key. Only properties specified by mask bits are updated. See AddImage(Texture2D, int, int, Color?, InlineAlignment, Rect2?, Variant, bool, string, bool).
public void UpdateImage(Variant key, RichTextLabel.ImageUpdateMask mask, Texture2D image, int width = 0, int height = 0, Color? color = null, InlineAlignment inlineAlign = InlineAlignment.Center, Rect2? region = null, bool pad = false, string tooltip = "", bool sizeInPercent = false)
Parameters
keyVariantmaskRichTextLabel.ImageUpdateMaskimageTexture2DwidthintheightintcolorColor?If the parameter is null, then the default value is
new Color(1, 1, 1, 1).inlineAlignInlineAlignmentregionRect2?If the parameter is null, then the default value is
new Rect2(new Vector2(0, 0), new Vector2(0, 0)).padbooltooltipstringsizeInPercentbool
Events
Finished
Triggered when the document is fully loaded.
public event Action Finished
Event Type
MetaClicked
Triggered when the user clicks on content between meta (URL) tags. If the meta is defined in BBCode, e.g. [url={"key": "value"}]Text[/url], then the parameter for this signal will always be a string type. If a particular type or an object is desired, the PushMeta(Variant) method must be used to manually insert the data into the tag stack. Alternatively, you can convert the string input to the desired type based on its contents (such as calling Parse(string, bool) on it).
For example, the following method can be connected to MetaClicked to open clicked URLs using the user's default web browser:
public event RichTextLabel.MetaClickedEventHandler MetaClicked
Event Type
MetaHoverEnded
Triggers when the mouse exits a meta tag.
public event RichTextLabel.MetaHoverEndedEventHandler MetaHoverEnded
Event Type
MetaHoverStarted
Triggers when the mouse enters a meta tag.
public event RichTextLabel.MetaHoverStartedEventHandler MetaHoverStarted