Advice on Communicating Child Class Events to Parent Class

gui

#1

So, I’ve got my main project ui class ‘PluginEditor’ and i’ve got a class for a custom toolbar which also has a class inside it for a custom drop down menu. I have a listener that identifies when the combobox item has changed from inside the custom drop down menu class but I want to return something to the parent class (PluginEditor) when it has changed, mainly to update something that exists in the parent class.

How can I get a callback/update to occur inside the parent class when an event is triggered in the child class?


#2

Have a look at change listeners.

Make your child class a ChangeBroadcaster and your parent class a ChangeListener. Implement the ChangeListenerCallback method in your parent class and then call sendChangeMessage() in your child class.

Edit:
Alternatively you could just add the parent as a listener to the combobox as well as or instead of the child.


#3

Having difficulty adding a listener to the parent for the child class mainly because it is actually a child of a child component and I want to receive events from the child child back to the parent. To give you an overview, I have a toolbar which is the child to the main PluginEditor class and then I have custom combobox which is the child of the child toolbar.

Edit: From what i see I need to add the listener using the method addListener but unfortunately the child child doesn’t live inside the parent but in the child class so I don’t have access to it to add a listener to it…


#4

addListener() just takes a pointer to a class derived from the appropriate listener class (in this case ComboBox::Listener). So when you call addListener() on your combobox (presumably you do this in your custom toolbar class?) then you just need to pass a pointer to the parent class.

To get a pointer to the parent in the toolbar class, have the toolbar class take a pointer to the parent as an argument in it’s constructor. Then in that constructor call addListener on the box and pass in the pointer. In the parent class you can then just pass the ‘this’ pointer to the toolbar.

Something like this:

class Parent : public Component,
               public ComboBox::Listener
{
public:
    Parent() : bar(this) {}

private:
	CustomToolbar bar;
};

class CustomToolbar : public Component
{
public:
	CustomToolbar(Parent* p)
	{
		box.addListener(p);
	}

private:
	CustomComboBox box;
};

class CustomComboBox : public ComboBox
{
	/*...*/
};

#5

Can’t you just do

addListener->( dynamic_cast<ComboBox::Listener *>(getParentComponent()->getParentComponent()) )

?


#6

Never thought to do getParentComponent()->getParentComponent()!:thinking:
That’d be a simpler way than my method!