TGUI Forum

General Category => Help requests => Topic started by: Kratos on 17 May 2019, 13:57:34

Title: Cast Widget to Radiobutton?
Post by: Kratos on 17 May 2019, 13:57:34
Hi Texus!

First, thank you for your amazing Library, I'm using version 0.8.5 now.

I used the gui builder to create a form, and in my code I'ld like to see if a checkbox (or radiobutton) is checked or not. I tried the following:
if (((tgui::RadioButton*)((tgui::ClickableWidget*)NewGameMenu->get("radTom"))->isChecked()) but unfortunately without success.

Is there something special I have to do to cast from a pointer to a widget to a Radiobutton? Because it doesn't inherit directly from Widget.

Thank you,

Tom.
Title: Re: Cast Widget to Radiobutton?
Post by: texus on 17 May 2019, 18:21:36
Widget pointers are of type std::shared_ptr (tgui::Widget::Ptr is just an alias for std::shared_ptr<Widget>), so you shouldn't just cast them to raw pointers.You could call the .get() function of std::shared_ptr<T> to get a T* which you can then cast with a dynamic_cast (or with a c-style cast like you are doing), but it isn't meant to be used like that.
You can cast std::shared_ptr objects with std::dynamic_pointer_cast but to make things shorter widgets have a cast function that does it for you. So you can write something like
tgui::RadioButton::Ptr = widget->cast<tgui::RadioButton>();

There is actually a get function that takes a template parameter and does the cast for you, so what you want is as simple as
NewGameMenu->get<tgui::RadioButton>("radTom")->isChecked()
Title: Re: Cast Widget to Radiobutton?
Post by: Kratos on 19 May 2019, 18:17:21
Okay. I tried it like that and it works like a charm!

This is great! Thanks.