TreeItem in Godot – Complete Guide

Welcome to our tutorial on the TreeItem class in the Godot Engine 4, designed to help you master the fine art of GUI controls within your game development process. Godot Engine is a versatile and powerful open-source game engine that’s gaining momentum within the game development community, thanks to its user-friendly interface and a wide array of features. Within this engine, TreeItem plays a critical role in creating hierarchical lists, an essential component for in-game menus, inventories, or any complex nested structures. Strap on your game dev helmets, as we delve into the tree-like structures of Godot, where branching out is a literal function of the design!

What is TreeItem?

The TreeItem class is a fundamental building block within Godot’s Tree control. It represents a single element within a Tree that can have its own subitems, effectively letting you create a structured, hierarchical interface. Think of TreeItem as a box that cannot only contain text and buttons but also smaller boxes, neatly organizing your game’s options or inventory in a visual tree-like structure.

What is TreeItem Used For?

TreeItems are the core elements that make up a Tree control. This control can be used to craft complex UI elements where users need to navigate through layers of information. For instance, you might use them to build:

– An in-game menu with categorized settings
– A file browser within your game’s level editor
– A detailed inventory system for an RPG game

Why Should I Learn About TreeItem?

Understanding TreeItem is crucial for game developers who aim to provide an intuitive and user-friendly interface in their games. Learning to manipulate these controls will allow you to present organized content that players can easily interact with. Whether it’s for a skill tree in an RPG, a complex item management system, or a debug console for your game, mastering TreeItem will empower you to build sophisticated and functional UIs. Plus, it’s a stepping stone towards comprehending more advanced UI development within Godot or other game engines, making it a valuable addition to your game development toolkit.

CTA Small Image

Creating a Basic Tree Structure

To get started with TreeItem, you’ll need to create a base Tree control node which will serve as the parent for all TreeItems. The following code shows how to create a Tree node and add it to the scene:

var tree =

Now, let’s add our first TreeItem to the tree. A TreeItem cannot exist on its own—it must belong to a Tree. Here’s how you can create a root item for the tree:

var root = tree.create_item()
root.set_text(0, "Root Item")

Note that set_text() takes two arguments: the column index where you want to set the text (0 for the first column), and the text itself.

Adding Child Items

What’s a tree without its branches? Adding child items to a TreeItem will start to form the hierarchy that’s representative of a tree structure. Below is a method of adding child elements to the root item:

var child1 = tree.create_item(root)
child1.set_text(0, "Child 1")

var child2 = tree.create_item(root)
child2.set_text(0, "Child 2")

These children will now appear underneath the “Root Item” in the tree.

Customizing TreeItem Appearance

You’re not limited to simple text; TreeItems can also hold icons, checkboxes, and custom fonts. Here’s how you can customize your TreeItem to have an icon:

var icon_texture = load("res://icon.png")
root.set_icon(0, icon_texture)

Furthermore, you can make a TreeItem editable, selectable, and checkable like so:

root.set_editable(0, true)
child1.set_selectable(0, true)
child2.set_checkbox(0, true)

Now your root item is editable, meaning the user can change the text. Child 1 is selectable, and Child 2 has a checkbox next to it.

Navigating and Selecting TreeItems

Part of what makes the Tree UI element so powerful is the ability to navigate through items and react to user interactions. Here’s an example of how to connect a signal when a TreeItem is selected:

tree.connect("item_selected", self, "_on_Tree_item_selected")

func _on_Tree_item_selected():
    var selected_item = tree.get_selected()
    if selected_item != null:
        print(selected_item.get_text(0))  # Output the text of the selected item

This code will print the text of the selected TreeItem to the console.

Expanding and Collapsing Items

To achieve a truly interactive tree structure, you’ll want to give users the ability to expand and collapse TreeItems to show or hide their child elements. Here’s how to do just that:

root.set_collapsed(true)   # This will collapse the root item by default
child1.set_collapsed(false)  # Child 1 will be expanded

This will collapse the root item when the tree first appears, but leave “Child 1” expanded. To toggle the collapsed state of an item in the runtime, you can call set_collapsed() on the TreeItem instance with the desired state.

In the next segment, we will extend these basics and show you how to handle more complex cases, such as handling buttons and custom controls within TreeItems.

Moving beyond simply displaying items, we can integrate a range of different control types directly within our TreeItems. Each cell in a TreeItem can be customized with its own unique control. Let’s start by adding a button to our tree structure.

var button =
button.text = "Click Me"
root.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
root.set_custom_draw(0, button)

This code snippet creates a Button instance and assigns it to the root TreeItem cell. The set_cell_mode() method is used to define how the cell content should be managed, while set_custom_draw() attaches the button to the cell.

Perhaps your game requires an option to rate items from a list. We could use a Range control, like a Slider, within a TreeItem for the user to set a rating:

var slider =
slider.min_value = 1
slider.max_value = 5
slider.step = 1
child1.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
child1.set_custom_draw(0, slider)

We’re setting the minimum and maximum values to define the slider range, and thanks to the set_custom_draw() method, it will be rendered within “Child 1”.

If your game has a color-coded inventory system or needs a color selection feature, a ColorRect control can be included within a TreeItem:

var color_rect =
color_rect.color = Color(1, 0, 0)  # Red color
child2.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
child2.set_custom_draw(0, color_rect)

The ColorRect has its color property set to red, and it’s added to “Child 2”. Now, each time the player sees this TreeItem, a red color will be displayed.

For text input directly within a tree, such as renaming an item in-game, you could embed a LineEdit control:

var line_edit =
line_edit.placeholder_text = "Type your text"
child2.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
child2.set_custom_draw(0, line_edit)

With the LineEdit in place, users can click and type directly into the tree. Each TreeItem can effectively hold its own mini form for user interaction.

Finally, we must be able to react when these custom controls are being interacted with. Let’s create a signal connection for the button within our TreeItem:

button.connect("pressed", self, "_on_button_pressed", [root])

func _on_button_pressed(item):
    print("Button in item with text %s was pressed" % item.get_text(0))

Here, we connect the button’s “pressed” signal to a function in our script. When pressed, the button will output a message indicating which TreeItem’s button was pressed using the text from that item as part of the message.

These examples show how Godot’s TreeItems can be customized to include diverse controls/icons and how to respond to user interactions within your game UI. As you continue to experiment with TreeItems, you’ll find they are a vital part of creating a rich and interactive user interface, making them an essential tool in your Godot development skills.

Let’s explore more interactable controls that we can embed within our TreeItem cells to enhance the UI of our Godot games. Suppose we want to give our users the ability to choose from a dropdown list. We can use an OptionButton for this:

var option_button =
option_button.add_item("Option 1")
option_button.add_item("Option 2")
option_button.add_item("Option 3")
child1.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
child1.set_custom_draw(0, option_button)

This code adds an OptionButton with three different options to “Child 1”. Players can now pick one of the predefined options directly within the tree.

Combining multiple controls within a single TreeItem allows for even richer interactions. For instance, we might want to include both text and a button in one line:

var text_label =
text_label.text = "Press the button:"
child2.set_cell_mode(0, TreeItem.CELL_MODE_CUSTOM)
child2.set_custom_draw(0, text_label)

var action_button =
action_button.text = "Action"
child2.set_cell_mode(1, TreeItem.CELL_MODE_CUSTOM)
child2.set_custom_draw(1, action_button)

Here we added a Label to the first cell and a Button to the second cell of “Child 2”. This setup can be useful for pairing actions with descriptions or commands with their explanations.

TreeItems can also be used to create toggles for activating or deactivating game features:

var toggle =
toggle.text = "Enable feature"
root.set_cell_mode(1, TreeItem.CELL_MODE_CUSTOM)
root.set_custom_draw(1, toggle)

The CheckBox control is set to the second cell of the root TreeItem, acting as a toggle for a hypothetical game feature.

When organizing items within a Tree structure, we often need to enable users to reorder items. Implementing drag and drop functionality could look something like this:

# Assuming 'tree' is already an initialized Tree node with multiple TreeItem children
tree.connect("tree_empty_rmb_selected", self, "_on_tree_empty_rmb_selected")

func _on_tree_empty_rmb_selected(position):
    var item = tree.get_item_at_position(position, true)
    if item != null:
        item.set_custom_minimum_height(50)  # just as an example
        print("You right-clicked on: ", item.get_text(0))

This setup enables dragging of all elements within the tree and reacts to a right-mouse-button event on an empty area, providing a basis from which we could expand into custom drag-and-drop behavior.

Finally, it might be useful to have progress bars in our game’s UI, showing the progress of certain tasks or the health of a player:

var progress_bar =
progress_bar.value = 50  # Set this to whatever the current progress is
progress_bar.max_value = 100
child1.set_cell_mode(1, TreeItem.CELL_MODE_CUSTOM)
child1.set_custom_draw(1, progress_bar)

This code snippet puts a ProgressBar into the second cell of “Child 1”, which can visually represent any measurable progress within the game.

By utilizing the flexible TreeItem class in Godot, we can create a variety of custom UI elements within our games. The examples given above are just a starting point and can be expanded and modified to suit the specific needs of your game. It’s the combination of these many small yet customizable components that allows game developers to craft unique and intuitive user interfaces that engage and inform the player, ultimately enhancing the gaming experience.

Continue Your Game Development Journey

You’ve taken great strides in understanding the TreeItem class and how it can be employed within the Godot Engine to enhance your game’s UI. While this knowledge is incredibly valuable, it’s merely a piece of the larger game development puzzle.

To keep growing as a game developer and broaden your skills, we invite you to explore our Godot Game Development Mini-Degree. Our extensive program will guide you through the process of building cross-platform games using the latest iteration of the Godot Engine. From mastering 2D and 3D assets to coding with GDScript and implementing robust gameplay mechanics, you’ll engage in hands-on projects that can bolster your portfolio and enhance your dev toolkit.

Whether you’re a beginner or looking to level up, our catalog of Godot courses caters to a wide spectrum of learning needs. With Zenva, you can set your own pace with our flexible, project-based courses, accessible anytime and anywhere. Step into the world of game development with confidence and the backing of Zenva’s high-quality content to fuel your journey from novice to pro.


You’re now armed with the knowledge to employ the TreeItem class in your Godot Engine projects, paving the way for creating complex and interactive UI structures that can immensely elevate the player’s experience. Your gaming worlds can now be enriched with sophisticated interfaces that are not only functional but also engaging to navigate. But this is merely a new beginning on your path to becoming a seasoned game developer.

Embrace the excitement of learning and dive deeper into the full spectrum of game development with our Godot Game Development Mini-Degree. Give life to your creative visions, tackle new challenges, and expand your skillset with us at Zenva, where your journey from learning to mastering game development is respected, supported, and encouraged. Let’s build amazing games together.

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.