UI Layout using Containers

The official Docs do a good job of explaining the basics of UI Containers. But here are extra tips and examples.

Avoiding problems with z-index

When a 2D scene uses z-order to layer nodes, the UI components may be covered over. Here, icon1 has its z-index set to 1. This causes Button1 to be obscured.

z-index

The solution is to use a CanvasLayer node as a parent to the UI.

How to make Control nodes stick to the top and bottom of the viewport

We can use a VBoxContainer and push the top and bottom parts of the UI apart with a Control node with its Vertical Size Flag set to Expand. And also, we may add spacer controls for margin.

Vertical layout

The buttons have their Min Size x width set, and their Horizontal Shrink Center Size Flag set (Fill unchecked).

The top and bottom spacers have their Min Size y values set to 20 pixels. The MidSpacer has its Vertical Size Flag set to Expand.

So, you can see how the Control node is useful for pushing nodes apart and remains invisible.

When many items are equally spaced, we tend to set the Separation value under Custom Constants for the VBoxContainer or HBoxContainer.

Connecting to UI Nodes

We should connect signals from Buttons to our main script. This is easily done manually in the Editor. And when we relocate elements, maybe changing their position in the Tree, the Editor should keep track of the changes to the signal connection path.

When connecting via code, we may use the find_node method to avoid breaking the path to the Control. And also use find_node to establish a path to items to update such as Labels. This allows us to freely nest many Nodes, and alter the structure when creating a complex UI.

Responding to the Mouse and other User Input Events

In order to detect mouse clicks and the Mouse entering and leaving the area of a Control Node, the Mouse Filter settings must be correct. The downstream Node must PASS or IGNORE Input Events in order for ancestor Nodes to receive the event. If it is set to STOP, then ancestor Nodes will not be able to detect the events.

This is a common problem when you wonder why the Mouse is being ignored.

More solutions