Download

How to get reference to parent widget to call function

Suppose I have a widget called ‘Child_Widget’ which is a canvas panel containing a button. I then place a few of these inside another called ‘Parent_Widget’, but they might be nested in several layers in the hierarchy - inside a horizontal box, which is inside a scale box, which is inside a canvas panel, for example.

And suppose the ‘Parent_Widget’ contains a function called ‘Parent_Function’.

On BeginPlay, I want the button inside ‘Child_Widget’ to contain a reference to ‘Parent_Widget’ so that OnClick it can call 'Parent_Widget’s ‘Parent_Function’ - what is the correct way to do this?

I have tried using (on ‘Child_Widget’) the Get Parent node and then casting the result as a ‘Parent_Widget’ but the cast fails.

The most basic option is to create a variable type Parent_Widget on your children and have the parent set the reference. The children can then directly access whatever functions/variables the parent has.

Alternatively, set up an Event Dispatcher to call an event on the parent. These may be quite confusing initially, though.

Check these out:
Direct Communications
Event Dispatcher

Thanks! That’s very helpful. I’ll try out the first method.