In MATLAB, can a class method act as a uicontrol callback without being public?
-
01-07-2019 - |
Question
In MATLAB 2008a, is there a way to allow a class method to act as a uicontrol callback function without having to make the method public? Conceptually, the method should not be public because it should never be called by a user of the class. It should only be called as a result of a UI event triggering a callback. However, if I set the method's access to private or protected, the callback doesn't work. My class is derived from hgsetget and is defined using the 2008a classdef syntax.
The uicontrol code looks something like:
methods (Access = public)
function this = MyClass(args)
this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ...
{@(src, event)myCallbackMethod(this, src, event)});
% the rest of the class constructor code
end
end
The callback code looks like:
methods (Access = private) % This doesn't work because it's private
% It works just fine if I make it public instead, but that's wrong conceptually.
function myCallbackMethod(this, src, event)
% do something
end
end
Solution
Storing the function handle of the callback as a private property seems to workaround the problem. Try this:
classdef MyClass
properties
handle;
end
properties (Access=private)
callback;
end
methods
function this = MyClass(args)
this.callback = @myCallbackMethod;
this.handle = uicontrol('Callback', ...
{@(src, event)myCallbackMethod(this, src, event)});
end
end
methods (Access = private)
function myCallbackMethod(this, src, event)
disp('Hello world!');
end
end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow