Check if mouse is above an axes
18 views (last 30 days)
Show older comments
Justin Solomon
on 27 May 2015
Commented: Walter Roberson
on 26 Jun 2020
Is there a quick way to check if the mouse is currently positioned over an axes? I'm working on a GUI that sets the 'WindowScrollWheelFcn' property of the figure. However, I only want the callback function to do something if the mouse is currently over a given axes. I've been using the 'CurrentPoint' property of the figure, and then using the position property of the axes to check if the mouse is over the axes. This works fine when the axes' parent is the figure. However, for my GUI, its possible that the axes is contained in several hierarchies of uipanels, thus the axes' position property is relative to its parent panel, not the figure. This makes figuring out if the mouse is over the axes more complicated. I need this to work, independent if the axes is contained in the figure, or in a uipanel that is a descendent of the figure. Any clever ideas out there? Thanks in advance for any tips.
0 Comments
Accepted Answer
Joseph Cheng
on 28 May 2015
Here is a little thing i threw together.
function test()
h = figure(1);
hp = uipanel('Title','Main Panel','FontSize',12,...
'BackgroundColor','white',...
'Position',[.1 .1 .9 .9]);
hsp = uipanel('Parent',hp,'Title','Subpanel','FontSize',12,...
'Position',[.1 .1 .9 .9]);
hax = axes('Parent',hsp,'position',[.1 .1 .8 .8]);
plot(randi(10,4,2));
set(h,'windowbuttonmotionfcn',@mousemove);
function mousemove(hobject,eventdata)
C = get(gca,'currentpoint');
P = get(gca,'position');
xlim = get(gca,'xlim');
ylim = get(gca,'ylim');
outX = ~any(diff([xlim(1) C(1,1) xlim(2)])<0);
outY = ~any(diff([ylim(1) C(1,2) ylim(2)])<0);
if outX&outY
set(gca,'color',[0 1 0])
else
set(gca,'color',[1 0 0])
end
title(gca, {['(X,Y) = (', num2str(C(1,1)), ', ',num2str(C(1,2)), ')'];...
[num2str([outX outY])]})
now obviously you'll have to adapt and see if it is what you're looking to do. I didn't have time to add some robustness checks for multiple axes but this mayget you where you need to go. So instead of looking at whether the mouse is within the axes position, i chose to check to see if the point is within the x and y limits of the axes.
2 Comments
Joseph Cheng
on 28 May 2015
oh and i changed the logic checks so the outX and outY actually should be inX and inY. Just didn't get around to changing it when i put the ~ infront of the any.
More Answers (1)
Jan
on 28 May 2015
overobj helps to check if the mouse is on top of an axes. See http://undocumentedmatlab.com/blog/undocumented-mouse-pointer-functions
See Also
Categories
Find more on Migrate GUIDE Apps in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!