Mike-C
Mike-C

Reputation: 43

Matlab: Get value from popup menu before choosing an item

I’m working on a GUI with a couple of popup menus. The problem is, if you run the program and you don’t choose anything from the menu, the value is set on what it was the last time I ran the program. I got this in my opening function (tag_port and tag_speedunit are the tags for two of the popup menus):

 set(handles.tag_port,'Value',1);
set(handles.tag_speedunit,'Value',1);

But that doesn’t work. By changing the value it only changes which item is shown in the popup menu when running the program, but if you don’t pick anything it is still stuck on what you picked last time you ran it.

my popup funktion looks like that:

function tag_port_Callback(hObject, eventdata, handles)
% That'll give me all the Choices in the popup menu
contents = get(hObject,'String');
% That'll give the value of the specific choice
popChoice = contents{get(hObject,'Value')};
setappdata(0,'popChoice',popChoice);

%end of every funktion
guidata(hObject,handles);

and in my main function I'm asking for the value:

popChoice = getappdata(0,'popChoice')

But as I said popChoice won't give me the popup value '1' unless i choose it by clicking on it.

Any ideas??? Thanks so much in advance.

Upvotes: 0

Views: 433

Answers (1)

Suever
Suever

Reputation: 65450

The issue is because setting the value programmatically does not trigger the callback, only explicit actions by the user will trigger the callback. You really have two options:

  1. Set the popChoice value at the beginning when you set the Value.

    set(handles.tag_port,'Value',1);
    set(handles.tag_speedunit,'Value',1);
    
    % Set the default value here
    setappdata(0, 'popChoice', 'defaultvalue')
    
  2. Trigger the callback manually within the opening function

    set(handles.tag_port, 'Value', 1)
    set(handles.tag_speedunit, 'Value', 1)
    
    % Trigger the callback
    tag_port_Callback(handles.tag_port, [], guidata(handles.tag_port))
    

Upvotes: 1

Related Questions