ItemList in Godot – Complete Guide

Welcome to our tutorial on Godot 4’s ItemList class—a versatile and powerful component for developing user interfaces in your games and applications. As aspiring or seasoned developers, understanding how to utilize UI elements effectively is critical for creating engaging and intuitive experiences for your players. The ItemList class is particularly noteworthy for its functionality in displaying a scrollable list of selectable items, making it an essential tool to master within the Godot engine.

What Is ItemList?

ItemList is an invaluable UI control in Godot 4 that provides a vertical list of selectable items which can span across one or multiple columns. Each item within this list can be adorned with text and an associated icon, enhancing the visual appeal and user clarity.

What Is It For?

ItemList can be used for various in-game scenarios such as inventories, menus, dialogue options, or any situation where a list selection is required. This control supports features like reselection, context menu opening through right-click, and double-clicking or pressing Enter to activate items, offering a rich set of functionalities for developers to take advantage of.

Why Should I Learn It?

Learning to implement ItemList is beneficial for various reasons:
– It provides a smooth user experience with its built-in selection and navigation capabilities.
– The control is flexible, with support for single or multiple columns and customization options such as icon placement and size.
– It also promotes accessibility, with increment search options to quickly navigate through list items.

By mastering ItemList, you’ll be able to create functional and visually-appealing UI elements that can dramatically improve the interaction aspect of your Godot projects. Whether you’re a beginner just starting out or an experienced coder looking to polish your UI skills, getting to grips with ItemList is a step toward building more engaging and professional games.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating an ItemList

To start using an ItemList, first, you need to create one in your scene. Drag the ItemList node from the Create Node window into your scene. Here’s how you’d typically create an ItemList through code and add items to it:

var item_list = ItemList.new()
add_child(item_list)
item_list.size_flags_vertical = Control.SIZE_EXPAND_FILL

item_list.add_item("Item 1")
item_list.add_item("Item 2")
item_list.add_item("Item 3")

Then, to make it interactive, let’s enable multiple selections:

item_list.select_mode = ItemList.SELECT_MULTI
item_list.multiselect = true

This simple extension allows users to select more than one item at a time.

Handling Selection Events

To react to selections, you need to connect the “item_selected” and “multi_selected” signals. Here is how you can do that:

item_list.connect("item_selected", self, "_on_item_selected")
item_list.connect("multi_selected", self, "_on_multi_selected")

func _on_item_selected(index):
    print("Item Selected: %s" % item_list.get_item_text(index))

func _on_multi_selected(index, selected):
    print("Item %d selection state: %s" % [index, selected])

These signals trigger the connected functions when an item’s selected state changes, allowing you to manage user interactions effectively.

Customizing Items

ItemList allows you to customize items with icons, disabled state, and tooltips. Below are examples of how to do that:

# Adding an item with an icon
var icon_texture = preload("res://path_to_your_icon.png")
item_list.add_item("Item with Icon", icon_texture)

# Disabling an item (it cannot be selected)
item_list.set_item_disabled(0, true)

# Adding a tooltip to an item
item_list.set_item_tooltip(1, "This is an item tooltip")

These customizations can significantly enhance the user experience by providing visual cues and information.

Reacting to Double-clicks or Activation

Sometimes you want to trigger an action when an item is double-clicked or activated (with Enter key). You’ll need to connect to the “item_activated” signal:

item_list.connect("item_activated", self, "_on_item_activated")

func _on_item_activated(index):
    print("Item Activated: %s" % item_list.get_item_text(index))

Activation signals can be especially useful for things like game menus or starting a selected level.

Now that you have a basic grasp on creating and customizing an ItemList along with handling selections and double-click activations, you can begin to experiment with these building blocks to create comprehensive lists within any Godot interface. Remember to test your creation by running the scene and interacting with the list – this is where you’ll see the immediate effects of your code and feel the satisfaction of what you’ve built. Try different combinations, experiment with the properties, and explore the diverse capabilities of the ItemList class to develop a more polished and engaging UI experience in your games.Scrolling through the ItemList is also a feature that can enhance the user’s navigation experience. By default, the ItemList comes with a scrollbar which appears when the number of items exceeds the visible area of the control. But suppose we want to scroll through the list programmatically. In that case, we can manipulate the ‘scroll_vertical’ property:

# Scroll to the bottom of the list
item_list.scroll_vertical = item_list.get_max_scroll()

# Scroll to the top of the list
item_list.scroll_vertical = 0

Finding and selecting an item by its text can be useful, especially when dealing with large lists. Here’s how you might find an item with the exact text “Item 2” and select it:

var items = ["Item 1", "Item 2", "Item 3"]
for i in range(items.size()):
    item_list.add_item(items[i])
    if items[i] == "Item 2":
        item_list.select(i, true)

Additionally, there are situations where you might need to clear the selection, remove items, or clear the entire list. Below are snippets that show you how to accomplish these tasks:

# Clear the selection
item_list.unselect_all()

# Remove an item
item_list.remove_item(1)

# Clear the entire list
item_list.clear()

Creating categories within your ItemList can help organize items, which is especially useful when dealing with long lists, such as inventories or song selections. Here is how you can add categories:

item_list.add_item("Category 1")
item_list.set_item_selectable(item_list.get_item_count() - 1, false)
item_list.add_item("Item under Category 1")

In the code above, we’ve added a category by creating an unselectable list item. Any items added after this can be considered part of that category.

Godot also enables drag-and-drop functionality within ItemList. You can enable it and receive a notification when an item is dropped:

item_list.set_allow_rmb_select(true)
item_list.set_drag_forwarding(item_list)

item_list.connect("item_rmb_selected", self, "_on_item_rmb_selected")

func _on_item_rmb_selected(index, at_position):
    print("Right-clicked item: %s at position: %s" % [item_list.get_item_text(index), at_position])

This sets up the option for an item to be right-clicked, potentially to initiate a drag operation, and to notify your script when right-clicking occurs.

Lastly, to get the currently selected items, especially after enabling multiple selections, you would access ‘get_selected_items()’ like so:

func _print_selected_items():
    var selected_items = item_list.get_selected_items()
    for i in selected_items:
        print("Selected: %s" % item_list.get_item_text(i))

# Call this function to print all currently selected items
_print_selected_items()

By leveraging these code examples, you can adapt the ItemList to suit complex scenarios and create a user interface that is not only functional but also intuitive and responsive to your users’ input. Remember to play around with these examples, combine them with your own use cases, and explore even more methods and properties provided by the ItemList class to tailor your Godot project’s UI to your specific needs.Let’s delve deeper into Godot 4’s ItemList features. One common requirement is to change the appearance of items, such as their individual custom background colors. Here’s how to achieve this:

# Assign custom colors to items
item_list.add_item("Red Item")
item_list.set_item_custom_bg_color(0, Color(1, 0, 0, 1)) # Red background

item_list.add_item("Green Item")
item_list.set_item_custom_bg_color(1, Color(0, 1, 0, 1)) # Green background

Suppose you’re storing additional data for each item in your list. You can associate metadata with an item to hold any related information.

# Adding metadata to items
item_list.add_item("Sword")
item_list.set_item_metadata(0, {"damage": 10, "element": "fire"})

item_list.add_item("Shield")
item_list.set_item_metadata(1, {"defense": 15, "weight": "heavy"})

You can then retrieve the metadata when, for example, an item is activated:

func _on_item_activated(index):
    var metadata = item_list.get_item_metadata(index)
    print("Activated item has metadata: %s" % str(metadata))

Sorting your ItemList might be essential for a better user experience. Here’s a quick way to sort items alphabetically:

func _sort_items_alphabetically():
    item_list.sort_items_by_text()

However, what if the list is getting dynamically updated and you always want the last item to be visible? You can do this:

func _add_item_and_scroll(name):
    item_list.add_item(name)
    item_list.ensure_current_is_visible()

If you want to give your users the flexibility to resize the columns in your ItemList, you’d enable the “resizable_columns” property:

item_list.resizable_columns = true

This property is particularly useful when working with multiple columns, allowing the user to adjust the display according to their preference.

For those interested in internationalization and localization, Godot’s ItemList can also handle text translation on-the-fly:

# Assuming you have set up localization in your project
item_list.add_item(tr("HELLO_WORLD"))

In the example above, ‘HELLO_WORLD’ would be a key in your translation file that corresponds to the translated text.

Lastly, when it comes to aesthetics, you might want to adjust the spacing between items for a cleaner look:

# Adjust the vertical spacing between items
item_list.custom_minimum_size = Vector2(item_list.custom_minimum_size.x, 30)

Each of these examples unlocks another layer of functionality, letting you fine-tune the ItemList to create a truly custom experience. Feel free to integrate these snippets into your own projects, tweaking them as needed to fit your specific use cases. Remember, experimenting is essential in learning how these properties and methods behave and interrelate within your Godot UI creations.

Continuing Your Game Development Journey

Now that you’ve got to grips with the Godot engine’s ItemList class, you’re well on your way to mastering user interface elements within your game projects. Taking what you’ve learned here is only the beginning—there’s a world of game development knowledge waiting to be explored!

We encourage you to keep the momentum going by delving into our Godot Game Development Mini-Degree, a comprehensive series of courses that will guide you through building your own games using the remarkable features of Godot 4. Whether you’re starting fresh or building upon your existing skills, the mini-degree program caters to all levels of experience. It covers an array of essential topics from GDScript fundamentals, 2D and 3D game mechanics, to creating immersive gameplay experiences across different game genres. Not only will you gain valuable knowledge, but you’ll also be able to construct a robust portfolio to show off to potential employers or clients.

For those of you seeking to explore even more about Godot, have a look through our broader range of Godot courses. Each course at Zenva is designed to help you learn at your own pace, solidify your skills, and achieve your game development dreams. Take the next step and join a thriving community of developers who, like you, are driven by the passion to create and learn. Happy coding!

Conclusion

Whether your aspiration lies in crafting narratives through role-playing games, designing challenging puzzles, or developing the next big indie hit, mastering UI components like the ItemList is a step towards bringing your visions to life. As you journey through the realms of game creation, remember that each tool and technique you learn from the Godot Game Development Mini-Degree can become a fundamental piece of your development arsenal, enabling you to create interactive and polished titles that resonate with your audience.

Embrace the power of knowledge and continued education to transform the way you design and develop games. If you’re keen to further your adventure and hone your skills, don’t hesitate to revisit our Godot Game Development Mini-Degree and immerse yourself in a learning experience that sets the foundation for success. Join us at Zenva, where we strive to provide you with the resources and guidance needed to turn your game development dreams into reality. Happy developing!

FREE COURSES
Python Blog Image

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