Sharing mouse events between parent and child components


#1

Sorry, this is a newbie question.

I have a parent component that contains a child component. At the moment, the only way I can get the child component to receive mouse events is to explicitly pass them from the parent to the child. E.g.:

void ParentComponent::mouseDown (const MouseEvent& m) { childComponent->mouseDown (m); }

Silmilarly, the only way I can get the child to update the mouseCursor is to explicitly hunt the value from inside the parent. E.g.:

void ParentComponent::paint (Graphics& g) { // -snip- setMouseCursor (childComponent->getMouseCursor()); }

It seems like the parent component is blocking mouse control to and from the child. I’m sure I’m missing something. How do I get the child component to receive the mouse events directly?

Thanks!
-Dan


#2

Check out Component::addMouseListener()…


#3

Cheers, Jules. I’ve spent a few hours trying to figure out how to properly set up a MouseListener. I also searched through the juceDemo code and couldn’t find any examples.

Based on the description in the API docs, I believe the way it should work is that I setup a MouseListener in the child component, and then register it in the parent component by doing something like this in the parent component:

addMouseListener (childComponent->childMouseListener, true);
However that produces run-time failures as soon as the mouse enters the parent component. Also, the fact that the constructor MouseListener::MouseListener() does not appear in the API docs leads me to believe that I’m not meant to be creating a MouseListener by simply declaring one in the child component. (E.g. MouseListener* childMouseListener;)

Is there any example code out there that I could study to learn how to properly setup a MouseListener?

Thanks, and sorry if I’m making a lot of obvious mistakes.

-Dan


#4

Unless I’m misunderstanding you, it sounds like you are trying to force your child component to contain a MouseListener object. Components already derive from mouse listener. If you look at the inheritence list for Component, you’ll see MouseListener. As a result there is no need to set anything up, except implementing the MouseListener callbacks in your child component.

All you actually need to do is just do something like:

myChild = new ChildComponent();
addMouseListener(myChild, false); // false 'cos I’m assuming you don’t want to generate multiple events for interactions on the child.

Then in child, just override mouseDown() or whatever. Note that mouseDown will be catching events from both the parent and the child.


#5

Thanks, Valley. That works perfectly, of course, and clarifies some misconceptions I had. Cheers to Jules, too, for a very ellegant implementation. I’m a bit thick, so it’s just taking me a little while to come up the learning curve…


#6