Callbacks on (visually) nested components

16 views (last 30 days)
John Hughes
John Hughes on 8 Jan 2023
Answered: John Hughes on 8 Jan 2023
In the following minimal example, I create a figure, with an axes, and draw a very simple plot (a single dot). When I click on the dot, the dot's mouse-down callback is invoked, which is what I expected. But the mouse-down callback for the figure is invoked as well, which is not what I expected. Here's the result of a run where I click on the single dot in the figure:
>> mnwe
MasterMD
DotMD
>>
Why? I'd like to have a click on the background create a new dot, while a click on an existing dot "selects" it (e.g., changes its color/size a little for the user's sake). When I do that "selection" process, I don't want to also create a new dot at that location!
Any suggestions about how to get slightly more normal UI behavior?
function mnwe
close; % Get rid of stuff from prior failed/interrupted executions
hFig = figure( 'windowstyle', 'normal');
set(hFig,'WindowButtonDownFcn', @MasterButtonDown );
ax = axes ( 'parent', hFig, 'position', [0.0 0.0 1.0 1.0], 'nextplot', 'add' );
set(gca, 'XLim', [-4,4], 'YLim', [-4, 4]);
% draw a single dot
hPlot = plot (ax, [1], [1], '-ro', 'ButtonDownFcn', @DotMouseDown );
% callback from the user clicking on a dot
function DotMouseDown ( obj, event)
disp('DotMD');
pause(0.05);
end
% callback from the user clicking on empty space in the window
function MasterButtonDown ( obj, event)
disp('MasterMD');
pause(0.05);
end
figure(gcf);
end
Thanks in advance.

Answers (1)

John Hughes
John Hughes on 8 Jan 2023
I figured it out. The key is the distinction between "WindownButtonDownFcn" and "ButtonDownFcn". The former is called for all clicks in the window; the latter only for clicks that are not on some contained element (like my dot). Unfortunately, 'figure" doesn't seem to have (or respond to) ButtonDownFcn in the way I'd expect, so I had to apply that to the axes instead. (It's important that the axes cover the entire figure, of course!)
Here's a working version that does what I expected:
function mwe
close;
hFig = figure( 'windowstyle', 'normal');
%set(hFig,'ButtonDownFcn', @MasterButtonDown );
ax = axes ( 'parent', hFig, 'position', [0.0 0.0 1.0 1.0], 'nextplot', 'add' );
set(ax,'ButtonDownFcn', @MasterButtonDown );
set(gca, 'XLim', [-4,4], 'YLim', [-4, 4]);
% draw a single dot
hPlot = plot (ax, [1], [1], '-ro', 'ButtonDownFcn', @DotMouseDown );
% callback from the user clicking on a dot
function DotMouseDown ( obj, event)
disp('DotMD');
pause(0.05);
end
% callback from the user clicking on empty space in the window
function MasterButtonDown ( obj, event)
disp('MasterMD');
pause(0.05);
end
figure(gcf);
end

Categories

Find more on Graphics Object Properties in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!