“Error using get” using a 'addlistener' fu

2019-02-21 02:17发布

问题:

I have a problem in a Matlab GUI code. Let say for instance that I want to display in the console the value of a slider cursor in the GUI. But the fact is that I want to display it in real time, eg at each position of the cursor even if the click is still on, while moving it.

For this, I read on internet that the 'addlistener' function could help me. I put it in the slider_CreateFcn function like this :

function slider1_CreateFcn(hObject, eventdata, handles)
   h=addlistener(hObject,'Value','PostSet',@(~,~)slider1_Callback)

Then, I added a simple disp function in the callback function, like this :

function slider1_Callback(hObject, eventdata, handles)
    get(hObject,'value')

Running this code raise this error :

Warning: Error occurred while executing callback:
Error using get
Cannot find 'get' method for matlab.graphics.internal.GraphicsMetaProperty class.

Error in untitled>slider1_Callback (line xx)
get(hObject,'value')

If I remove the addlistener function, obviously the update is no more in real time, but I don't get the error message. So I think that the problem is directly coming from the addlistener function.

What is happening and how can I fix it?

回答1:

First of all, the code that you posted isn't the code that is producing your error. I'm guessing that the code that yielded your error looked like this:

h = addlistener(hObject, 'Value', 'PostSet', @slider1_Callback);

In this instance, a meta property is passed as the first input argument to slider1_Callback which is giving you the immediate error you're seeing.

That being said, if you want to call slider1_Callback you need to craft an anonymous function which actually passes the correct type (and number) of inputs to the callback function. Here is one which does that.

function slider1_CreateFcn(hObject, eventdata, handles)
    h = addlistener(hObject, 'Value', 'PostSet', ...
                    @(src,evnt)slider1_Callback(hObject, [], handles))
end

The better thing to do though, is to just use a separate callback rather then the one that GUIDE creates for you. This gives you a little bit more flexibility. Also, if you just want to display the value you don't need all of the other inputs and you can actually inline the entire callback rather than having a separate function.

h = addlistener(hObject, 'Value', 'PostSet', @(s,e)disp(get(hObject, 'Value')));

And to show it in action: