Creating, copying and removing widgets

TGUI 0.7 is no longer supported, use a newer TGUI version instead.

Creating widgets

Creating a widget goes in two steps: creating it and adding it to its parent.

Creating widgets is simple, just call the create function:

tgui::Button::Ptr button = tgui::Button::create();

When creating a widget like that, they will make use of the built-in "White" theme. No external resources are needed for them and you have something on your screen immediately. Although you can customize the widgets by changing property by property, you probably want to use themes to give your widgets a different look. TGUI already ships with some theme files that you can load and use out of the box.

The second step is to add the widget to its parent widget. Usually this is the Gui object, but it could also be e.g. a child window.

gui.add(button2, "MyUniqueName");

Retrieving widgets

Once a widget is added to a parent widget (or directly to the gui), you no longer have to store it yourself, you can just let your pointer go out of scope. When you need it later you can always get it back from the parent widget. The name that the get function takes as parameter was the optional parameter of the add function.

tgui::Widget::Ptr widget = gui.get("MyWidgetName");
tgui::Button::Ptr button = gui.get<tgui::Button>("MyUniqueName");

A common mistake is to call the get function on the wrong widget when you have a hierarchy. If you added the button to a child window, which was in turn added to the gui, then the gui will not know about the existence of the button. You should call the get function of the child window or you can alternatively do a recursive search from the gui if the name is unique:

widget = childWindow->get("SomeButton");
widget = gui.get("SomeButton", true);

Copying widgets

When you know the type of your widget then you can simply use the copy function. The copied widget is however not bound to the same parent widget, you must add it again. This is done so that you can e.g. make a copy of a widget inside a child window and then add the copy to another child window.

tgui::Button::Ptr newButton = tgui::Button::copy(oldButton);

It is of course possible that you do not know the type of the widget. If you have been storing all the widgets in a list and you want to copy the list then you cannot use the copy function. In this situation you must use the clone function instead.

std::vector<tgui::Widget::Ptr> newList;
for (auto& widget : oldList)

Removing widgets

Once a widget is no longer needed, you can remove it from its parent container.


You could also remove all widgets inside a container at once.