Main Content

Pass Mouse Click to Group Parent

This example shows how a group of objects can pass a mouse click to a parent, which operates on all objects in the group.

Objective and Design

Suppose you want a single mouse click on any member of a group of objects to execute a single button down callback affecting all objects in the group.

  • Define the graphics objects to be added to the group.

  • Assign an hggroup object as the parent of the graphics objects.

  • Define a function to execute when any of the objects are clicked. Assign its function handle to the hggroup object’s ButtonDownFcn property.

  • Set the HitTest property of every object in the group to off so that the mouse click is passed to the object’s parent.

Object Hierarchy and Key Properties

This example uses the following object hierarchy.

MATLAB Code

Create a file with two functions:

  • pickPatch — The main function that creates the graphics objects.

  • groupCB — The local function for the hggroup callback.

The pickPatch function creates three patch objects and parents them to an hggroup object. Setting the HitTest property of each patch to off directs mouse clicks to the parent.

function pickPatch
   figure
   x = [0 1 2];
   y = [0 1 0];
   hGroup = hggroup('ButtonDownFcn',@groupCB);
   patch(x,y,'b',...
      'Parent',hGroup,...
      'HitTest','off')
   patch(x+2,y,'b',...
      'Parent',hGroup,...
      'HitTest','off')
   patch(x+3,y,'b',...
      'Parent',hGroup,...
      'HitTest','off')
end

The groupCB callback operates on all objects contained in the hggroup. The groupCB function uses the callback source argument passed to the callback (src) to obtain the handles of the patch objects.

Using the callback source argument (which is the handle to hggroup object) eliminates the need to create global data or pass additional arguments to the callback.

A left-click on any patch changes the face color of all three patches to a random RGB color value.

function groupCB(src,~)
   s = src.Children;
   set(s,'FaceColor',rand(1,3))
end

For more information on callback functions, see Create Callbacks for Graphics Objects