Get a widget

  • 3 Replies
  • 56 Views
Get a widget
« on: 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)?

*

texus

  • *****
  • 1475
    • View Profile
    • Texus's Blog
Re: Get a widget
« Reply #1 on: 25 September 2019, 22:28:49 »
When you add a widget to the gui, you can optionally pass it a name.
gui.add(widget, "UniqueName");

Passing that name to the get function will return the widget:
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:
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:
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->"

Re: Get a widget
« Reply #2 on: 27 September 2019, 18:30:38 »
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).

Re: Get a widget
« Reply #3 on: 27 September 2019, 18:43:44 »
Done it all I need to do was to use gui.remove(gui.get(WidgetName)) to propery remove it.