Get a widget

Started by CatalinNic, 25 September 2019, 20:32:25


I'm wondering how to get a widget from the gui? I know IIRC there is the function get(string& name). How i can use that (I mean to provide an example)?


When you add a widget to the gui, you can optionally pass it a name.
Code (cpp) Select
gui.add(widget, "UniqueName");

Passing that name to the get function will return the widget:
Code (cpp) Select
tgui::Widget::Ptr widget = gui.get("UniqueName");

The normal get function returns a pointer to the Widget class, which is the base class for all widgets. Often you need access to the functions of a derived type (e.g. for setting the text of a button), in which case you need to cast it:
Code (cpp) Select
tgui::Button::Ptr button = widget->cast<tgui::Button>();

There is however also a get function that does both of these operations at once: it retrieves the widget by its name and casts it to the right type. It is called like this:
Code (cpp) Select
tgui::Button::Ptr button = gui.get<tgui::Button>("UniqueName");

Obviously, the widget with name "UniqueName" has to be a Button, if it was e.g. an EditBox then it might fail.
(I'm not sure if I made any guarantees about what would happen. Right now I believe it will just return a nullptr, but it is possible that it could change to e.g. assert in the future. So just don't use the wrong type.)

The same holds for any container widget. If you have a Group, Panel, ChildWindow or any other widget that inherits from the Container class then you can use the get functions on them too, just replace the "gui." in the examples above with "container->"


And curious, how i can delete a widget if the only way to access it is by using the get function without crashing the whole program? (I hope that's pretty specific).


Done it all I need to do was to use gui.remove(gui.get(WidgetName)) to propery remove it.