User1551892
User1551892

Reputation: 3384

How to make ListBox persistent in matlab

I am developing a GUI in matlab and it has a list box. I am planning to call the GUI function with some input arguments and one of arguments want to add in list box. Since default listbox in gui is not persistent, so every time when I call the gui function with input argument, things get override in list box. I am trying to find a way to declare list box as persistent. Below is the code which I am using to add items in listbox.

names = get (handles.plotLB, 'string') ;
set (handles.plotLB,'string',{varargin{1},names{:}}) ;

Upvotes: 0

Views: 106

Answers (1)

il_raffa
il_raffa

Reputation: 5175

There are several possibilities to define a "persistent" set of listbox items.

The easiest one is to define a default list while creating the GUI itself:

  • double clicking on the listbox in the GUIDE panel opens the Inspector
  • select the String property
  • clicking on the icon, opens the items editor in which you can write le default items

enter image description here

Then you can add to these default items the ones you provide as input by adding the following in the GUI OpeningFcn

handles.output = hObject;
handles.listbox1.String=[varargin{1},handles.listbox1.String{:}]
% Update handles structure
guidata(hObject, handles);

Another possibility is to define the default list in the OpeningFcn and then adding the one provided as input:

handles.output = hObject;
in_list={'default_item_1' 'default_item_2' 'default_item_3'}
handles.listbox1.String=[varargin{1},in_list]
% Update handles structure
guidata(hObject, handles);

You can also create a configuration file in which you define the default list; in this case you can read it in the OpeningFcn and then adding the one provided as input:

handles.output = hObject;
if(exist('save_listbox_string_config.txt'))
   fp=fopen('save_listbox_string_config.txt')
   C=textscan(fp,'%s');
   fclose(fp);
   handles.listbox1.String=[C{1}(1:end);varargin{1}']
end
% Update handles structure
guidata(hObject, handles);

This solution allows you the easlily manage the default list by addind / removing items.

Also, using the configuration file approach, you can save the listbox items when you close the GUI.

To do that, you have to add the following in the CloseRequestFcn:

fp=fopen('save_listbox_string_config.txt','wt')
C=handles.listbox1.String
for i=1:size(C)
   fprintf(fp,'%s\n',char(C(i)))
end
fclose(fp);

To make the GUI more flexlible, you can add a control (e. g. a menu item or a checkbox) allowing the user to select if to save or not the list in the config file.

Upvotes: 1

Related Questions