MATLAB provides the addlistener
function.
Listeners allow us to keep track of changes of an object's properties and act upon them. For example, we can create a very simple listener that will display a message in the command window when the 'YLim'
property of an axes
object is changed:
% Example using axes
ax = axes();
addlistener(ax, 'YLim', 'PostSet', @(src, evnt)disp('YLim changed'));
Try panning the axes or zooming in/out and see what happens. This works fine.
I need to do the same but using an uiaxes
instead.
Unfortunately, it looks like we are not allowed to do so. Try running the following example:
% Example using uiaxes
ax = uiaxes();
addlistener(ax, 'YLim', 'PostSet', @(src, evnt)disp('YLim changed'));
It throws this error:
Error using matlab.ui.control.UIAxes/addlistener While adding a PostSet listener, property 'YLim' in class 'matlab.ui.control.UIAxes' is not defined to be SetObservable.
I've read the articles Listen for Changes to Property Values and Observe Changes to Property Values and I learned that a property must be declared as SetObservable
to allow being listened:
classdef PropLis < handle
properties (SetObservable)
ObservedProp = 1 % <-- Observable Property
end
end
I've tried taking a look at the UIAxes
class definition via edit matlab.ui.control.UIAxes
but it's not possible because it's a P-file.
If 'YLim'
is not observable then how can I keep track of changes in this property?
I'm using App Designer in MATLAB R2018b.
We should attach the listener to the internal Axes
object, and not the UIAxes
itself. Try this:
hFig = uifigure();
hAx = uiaxes(hFig);
addlistener(struct(hAx).Axes, 'YLim', 'PostSet', @(src, evnt)disp("YLim changed"));
hAx.YLim = [0 2];
In case anybody is wondering, I found this via trial and error.
Tested on R2018a & R2018b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With