Search code examples
matlabmatlab-guidepopupmenu

Populating a popup menu with directory files


I'm trying to populate a popup menu from a GUI I made up with GUIDE. I'm doing as follows:

TestFiles = dir([pwd '/test/*.txt']);
TestList = [];

for i = 1:length(TestFiles)
    filename = TestFiles(i).name;
    TestList = [TestList filename];
end

set(handles.popup_test,'string',TestList);

I'm doing this inside the popup_test_CreateFcn method (I'm not really sure that is the right place though).

When trying to launch the GUI I keep getting this:

??? Attempt to reference field of non-structure array.

Error in ==> init>popup_test_CreateFcn at 101
set(handles.popup_test,'string',TestList);

Error in ==> gui_mainfcn at 96
        feval(varargin{:});

Error in ==> init at 19
    gui_mainfcn(gui_State, varargin{:});

Error in ==> @(hObject,eventdata)init('popup_test_CreateFcn',hObject,eventdata,guidata(hObject))


??? Error using ==> struct2handle
Error while evaluating uicontrol CreateFcn

So for some reason the set() method is not allowing me to populate the popup menu with TestList.

Any thoughts?

Thanks in advance.


Solution

  • Note that when you run your program, the first functions called are the "create functions"

    So when you do set(handles.popup_test,'string',TestList); inside popup_test_CreateFcn, the function doesn't know what is handles because it is known only after the "opening function". (If you try to print it inside the "create functions" it will be empty).

    You can do inside this function something like this:

    handles.popup_test=hObject;  %pass handles the popup menu object
    guidata(hObject, handles);
    

    And in the opening function XXXX_OpeningFcn(hObject, eventdata, handles, varargin) you can add:

    %...define TestList and other things you need
    set(handles.popup_test,'string',TestList);