MATLAB: How to create mouse movement event on UIAxes in APP Designer to catch cursor location on the axes

app designermouse movementuiaxes

I have a UIAxes created in App designer. now I want to show cursor's x y location when mouse is moving on the axe, not click.

Best Answer

Here are 2 methods to capture mouse coordinates within the axes of a figure.
In these demos the coordinates of the cursor's current point on the axes will appear in the text box. When the mouse leaves the axes, the textbox will clear.
Be aware of the limit in precision of CurrentPoint within axes (see this explanation). For example, you may not be able to select an exact coordinate such as (0,0).
Method 1: Use a pointer manager (requires Image Processing Toolbox)
Instead of using the WindowButtonMotionFcn which requires you to detect when the mouse enters the axes, use a pointer manager assigned to the axes that returns the axes' current point when the mouse is over the axes. This is more efficient than the WindowButtonMotionFcn.
Add this to you app's startup function.
Key components
% Code that executes after component creation
function startupFcn(app)
pm.enterFcn = [];
pm.exitFcn = @(~,~) set(app.CurrentPositionEditField, 'Value', '');
pm.traverseFcn = @(~,~) set(app.CurrentPositionEditField, 'Value',...
sprintf('%.2f, %.2f', app.UIAxes.CurrentPoint(1,1:2)));
iptSetPointerBehavior(app.UIAxes, pm)
iptPointerManager(app.UIFigure,'enable');
set(app.UIFigure,'WindowButtonMotionFcn',@(~,~)NaN) %dummy fcn so that currentpoint is continually updated
end
Method 2: Assign a WindowButtonMotion to the figure
As Mohammad Sami suggested, the WindowButtonMotion function is assigned in AppDesigner > Designer View > in the Component Browser select the figure handle > callback > WindowButtonMotionFcn.
Key components
  • app.UIAxes - handle to the app's axes
  • app.UIFigure - handle to the app's figure
  • app.CurrentPositionEditField - handle to the text box
  • UIFigureWindowButtonMotion() - See instructions above.
% Window button motion function: UIFigure
function UIFigureWindowButtonMotion(app, event)
% Determine if mouse is within uiaxes
cp = app.UIFigure.CurrentPoint;
isInAxes = cp(1) >= app.UIAxes.Position(1) && ...
cp(1) <= sum(app.UIAxes.Position([1,3])) && ...
cp(2) >= app.UIAxes.Position(2) && ...
cp(2) <= sum(app.UIAxes.Position([2,4]));
if isInAxes
% Update displayed coordinates
set(app.CurrentPositionEditField, 'Value',...
sprintf('%.2f, %.2f', app.UIAxes.CurrentPoint(1,1:2)))
else
% Clear displayed coordinates
set(app.CurrentPositionEditField, 'Value', '')
end
end