UI: Controls, Containers & Themes
Godot's editor is itself built with Godot's UI nodes, so the UI toolkit is complete: buttons, labels, sliders, text fields, item lists, trees, tabs, rich text with BBCode, popups. All UI nodes inherit from Control, a 2D node with a rectangle (position + size), anchors, focus handling for keyboard and gamepad navigation, and a theme.
Anchors or containers
There are two ways to place controls, and you'll mix them:
- Anchors and offsets pin a control's edges to fractions of its parent's rectangle. A health bar anchored to the top-left stays there at any window size; a pause label anchored to the centre stays centred. The Layout toolbar menu (the green anchor icon) has presets such as Full Rect, Center and Top Wide.
- Containers position and size their children automatically. Inside a container, children's anchors are ignored; you control them with size flags and minimum sizes instead.
| Container | Lays out children |
|---|---|
VBoxContainer / HBoxContainer |
in a column / row, with separation between them |
GridContainer |
in a grid with columns columns |
MarginContainer |
one child, inset by margins |
CenterContainer |
children centred at their minimum size |
PanelContainer |
children over a panel background (a StyleBox) |
ScrollContainer |
one child, scrollable |
HFlowContainer / VFlowContainer |
wrapping rows / columns, like text |
TabContainer, SplitContainer, AspectRatioContainer |
tabs, a draggable split, a fixed aspect ratio |
Size flags decide what a child does with spare space: SIZE_FILL (stretch to the cell, the default), SIZE_EXPAND (take a share of the leftover space; size_flags_stretch_ratio sets the share), SIZE_SHRINK_CENTER / SIZE_SHRINK_END. A dialog with a title, a body that takes all the spare height, and buttons on the right:
extends Control
# frames: 1
func block(block_name: String, min_size: Vector2) -> ColorRect:
var r := ColorRect.new()
r.name = block_name
r.custom_minimum_size = min_size
return r
func _ready():
size = Vector2(300, 200)
var margin := MarginContainer.new()
margin.name = "Margin"
margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
for side in ["left", "top", "right", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 10)
add_child(margin)
var column := VBoxContainer.new()
column.name = "Column"
column.add_theme_constant_override("separation", 8)
margin.add_child(column)
column.add_child(block("Title", Vector2(0, 30)))
var body := block("Body", Vector2(0, 40))
body.size_flags_vertical = Control.SIZE_EXPAND_FILL # takes the leftover height
column.add_child(body)
var row := HBoxContainer.new()
row.name = "Buttons"
row.add_theme_constant_override("separation", 4)
row.alignment = BoxContainer.ALIGNMENT_END # buttons pushed to the right
column.add_child(row)
row.add_child(block("Cancel", Vector2(60, 24)))
row.add_child(block("OK", Vector2(60, 24)))
await get_tree().process_frame # containers sort at the end of the frame
for c in [margin, column, column.get_node("Title"), body, row, row.get_node("Cancel"), row.get_node("OK")]:
print(c.name.rpad(8), " pos ", c.global_position, " size ", c.size)Margin pos (0.0, 0.0) size (300.0, 200.0)
Column pos (10.0, 10.0) size (280.0, 180.0)
Title pos (10.0, 10.0) size (280.0, 30.0)
Body pos (10.0, 48.0) size (280.0, 110.0)
Buttons pos (10.0, 166.0) size (280.0, 24.0)
Cancel pos (166.0, 166.0) size (60.0, 24.0)
OK pos (230.0, 166.0) size (60.0, 24.0)
The body got 180 − 30 − 24 − 2 × 8 = 110 px because it is the only child with the expand flag. Containers sort their children at the end of the frame, so sizes read straight after add_child are not final; that is what the await get_tree().process_frame is for. In the editor you set the same things in the Inspector: Layout > Container Sizing for size flags and Theme Overrides > Constants for separation and margins.
Buttons and signals
UI nodes report what the player did through signals: Button.pressed, BaseButton.toggled(on), Range.value_changed(value) (sliders, spin boxes, progress bars), LineEdit.text_submitted(text), ItemList.item_selected(index). In the editor, select the button, open the Node dock, double-click pressed and pick the receiving node; Godot writes the _on_button_pressed stub. In code, connect the signal to a method, which is a Callable:
extends VBoxContainer
# frames: 1
var score_label: Label
var volume_slider: HSlider
var mute_box: CheckBox
var clicks := 0
func _ready():
var button := Button.new()
button.text = "Click me"
add_child(button)
score_label = Label.new()
add_child(score_label)
volume_slider = HSlider.new()
volume_slider.min_value = 0
volume_slider.max_value = 100
volume_slider.step = 5
add_child(volume_slider)
mute_box = CheckBox.new()
mute_box.text = "Mute"
add_child(mute_box)
# Connect signals to methods (Callables). The editor's Node dock does the same.
button.pressed.connect(_on_button_pressed)
volume_slider.value_changed.connect(_on_volume_changed)
mute_box.toggled.connect(_on_mute_toggled)
update_label()
# Simulate the player: there is no mouse here, so emit / set values directly.
button.pressed.emit()
button.pressed.emit()
volume_slider.value = 73 # snapped to the step: 75
volume_slider.value = 75 # same value: no signal
mute_box.button_pressed = true # emits toggled(true)
volume_slider.set_value_no_signal(20)
print("slider now ", volume_slider.value, " (set without a signal)")
func update_label():
score_label.text = "Clicks: %d" % clicks
print("label: ", score_label.text)
func _on_button_pressed():
clicks += 1
update_label()
func _on_volume_changed(value: float):
print("volume -> ", value, "%")
func _on_mute_toggled(on: bool):
print("mute -> ", on)
volume_slider.editable = not onlabel: Clicks: 0
label: Clicks: 1
label: Clicks: 2
volume -> 75.0%
mute -> true
slider now 20.0 (set without a signal)
Setting value or button_pressed from code emits the same signals as the player would, which is handy for loading saved settings into a menu (the handlers apply them) and occasionally a trap (a feedback loop between two sliders). set_value_no_signal() and set_pressed_no_signal() change the control silently.
Keyboard and gamepad navigation
Every game menu must work without a mouse. Controls with focus_mode = FOCUS_ALL (buttons, sliders, line edits) can take focus, and the built-in ui_up/ui_down/ui_left/ui_right/ui_accept actions move between them and press them.
- Call
grab_focus()on the first button when a menu opens, or nothing is focused and the gamepad does nothing. - Godot picks neighbours by position. Fix odd jumps with
focus_neighbor_top/bottom/left/rightandfocus_next/focus_previous. - Style the focused state (the
focusStyleBox) so it is clearly visible.
HUD and pause menus
Put game UI under a CanvasLayer. Its children are drawn in screen space, on top of the world, and ignore Camera2D movement:
Level (Node2D)
├── Player (CharacterBody2D)
│ └── Camera2D
├── Ground (TileMapLayer)
└── HUD (CanvasLayer) layer = 1
├── MarginContainer anchors: Full Rect
│ └── HBoxContainer
│ ├── HeartsLabel (Label)
│ └── CoinsLabel (Label)
└── PauseMenu (Control) process_mode = When Paused, visible = false
└── CenterContainer
└── VBoxContainer
├── ResumeButton (Button)
└── QuitButton (Button)get_tree().paused = true stops _process, _physics_process and input for every node whose Process > Mode is Inherit (the default) or Pausable. The pause menu sets its mode to When Paused (PROCESS_MODE_WHEN_PAUSED) so it is the one thing that still runs.
extends Control # PauseMenu
@onready var resume_button: Button = %ResumeButton
func _ready() -> void:
process_mode = Node.PROCESS_MODE_WHEN_PAUSED
resume_button.pressed.connect(_on_resume_pressed)
%QuitButton.pressed.connect(get_tree().quit)
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("pause"):
toggle()
get_viewport().set_input_as_handled()
func toggle() -> void:
visible = not visible
get_tree().paused = visible
if visible:
resume_button.grab_focus()
func _on_resume_pressed() -> void:
toggle()The %ResumeButton syntax finds a node marked as a scene-unique name (right-click it in the Scene dock and choose Access as Unique Name), so the script keeps working when you move the button into another container. Because the menu itself runs while paused, its _unhandled_input can also close it.
Themes
A Theme resource holds colours, constants, fonts, font sizes, icons and StyleBoxes per control type (Button, Label, PanelContainer...). Assign it to a control and it applies to that control and all its descendants; set it as Project Settings > GUI > Theme > Custom to apply it everywhere. Lookup order for each item is: the control's own override → the nearest ancestor's theme → the project theme → Godot's default theme. A type variation is a named variant of a type ("TitleLabel" = a Label with a bigger font), chosen per control with theme_type_variation:
extends Control
# frames: 0
func _ready():
var theme_res := Theme.new()
theme_res.set_color("font_color", "Label", Color.WHEAT)
theme_res.set_font_size("font_size", "Label", 18)
# A type variation: "TitleLabel" is a Label with a bigger font.
theme_res.set_type_variation("TitleLabel", "Label")
theme_res.set_font_size("font_size", "TitleLabel", 32)
theme = theme_res # applies to this Control and everything below it
var panel := PanelContainer.new()
add_child(panel)
var title := Label.new()
title.theme_type_variation = "TitleLabel"
panel.add_child(title)
var hint := Label.new()
panel.add_child(hint)
var warning := Label.new()
warning.add_theme_color_override("font_color", Color.ORANGE_RED) # one-off override
panel.add_child(warning)
for pair in [["title", title], ["hint", hint], ["warning", warning]]:
var l: Label = pair[1]
print(pair[0].rpad(8), " size ", l.get_theme_font_size("font_size"), " colour ", l.get_theme_color("font_color").to_html(false))
var plain := Label.new() # not under the themed Control
print("unthemed".rpad(8), " size ", plain.get_theme_font_size("font_size"), " colour ", plain.get_theme_color("font_color").to_html(false))
plain.free()title size 32 colour f5deb3
hint size 18 colour f5deb3
warning size 18 colour ff4500
unthemed size 16 colour ffffff
The title inherits the colour from Label (variations fall back to their base type) but takes its own font size. In practice you build the theme visually: create a Theme resource, double-click it to open the Theme editor at the bottom, click Add Type and edit each item with a live preview. Keep per-control overrides for genuine one-offs; a game with fifty overrides is a game whose style can't be changed in one place.
Tip: For pixel-art or fixed-resolution games, set Project Settings > Display > Window > Stretch > Mode to
canvas_items(orviewportfor crisp pixel art) so the UI scales with the window instead of staying tiny on a 4K screen.
Test yourself
A button inside an HBoxContainer ignores the anchors you set. Why?
- Buttons can't have anchors
- Containers position and size their children; you control children with size flags and minimum sizes instead
- Anchors only work in 3D
- You must call
queue_redraw()
The game is paused with get_tree().paused = true, and now the pause menu doesn't react either. What is missing?
- The menu must be a Node2D
- The menu's process mode must be
PROCESS_MODE_WHEN_PAUSED(or Always) - Buttons can't be pressed while paused
- Call
grab_focus()on the root
Which connects a button's pressed signal to a method in Godot 4?
button.connect("pressed", self, "_on_pressed")button.pressed.connect(_on_pressed)button.on_pressed += _on_pressedconnect(button.pressed, _on_pressed())