MatLab指南:在列表框中添加/删除项

wlp8pajw  于 2022-11-15  发布在  Matlab
关注(0)|答案(2)|浏览(444)

我正在尝试创建一个列表框,我可以在其中动态添加或删除项。
设置如下所示:

不幸的是-从图片中可以看到-当我删除元素时,列表的总长度保持不变,而不是缩小列表,现在显示的列表包含空洞。
有谁知道如何避免这种行为?
到目前为止,这是我的删除按钮代码:

function btnDeleteLabel_Callback(hObject, eventdata, handles)
    selectedId = get(handles.listbox_labels, 'Value');        % get id of selectedLabelName
    existingItems = get(handles.listbox_labels, 'String');    % get current listbox list
    existingItems{selectedId} = [];                   % delete the id
    set(handles.listbox_labels, 'String', existingItems);     % restore cropped version of label list
mzsu5hc0

mzsu5hc01#

删除“空”条目的最简单方法是用剩余的条目更新listbox字符串。
有三种可能性:

  • 第一个元素已删除:新列表将为upd_list={existingItems{2:end}}
  • 最后一个元素已被删除:新列表将为upd_list={existingItems{1:end-1}}
  • ANS中间元素已删除:新列表将为upd_list={existingItems{1:selectedId-1} existingItems{selectedId+1:end}}

您还可以检查列表的所有元素是否已被删除,在本例中,禁用“Delete”pushbutton;在本例中,您必须在“Add”callback中启用它。
您的btnDeleteLabel_Callback的可能实施可能是:

% --- Executes on button press in btnDeleteLabel.
function btnDeleteLabel_Callback(hObject, eventdata, handles)
% hObject    handle to btnDeleteLabel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

selectedId = get(handles.listbox_labels, 'Value')        % get id of selectedLabelName
existingItems = get(handles.listbox_labels, 'String')    % get current listbox list
%
% It is not necessary
%
% existingItems{selectedId} = []                   % delete the id

% Identify the items: if in the list only one item has been added the
% returned list is a char array
if(class(existingItems) == 'char')
   upd_list=''
   set(handles.listbox_labels, 'String', upd_list)
else
   % If the returned list is a cell array there are three cases
   n_items=length(existingItems)
   if(selectedId == 1)
      % The first element has been selected
      upd_list={existingItems{2:end}}
   elseif(selectedId == n_items)
      % The last element has been selected
      upd_list={existingItems{1:end-1}}
      % Set the "Value" property to the previous element
      set(handles.listbox_labels, 'Value', selectedId-1)
   else
      % And element in the list has been selected
      upd_list={existingItems{1:selectedId-1} existingItems{selectedId+1:end}}
   end
end
% Update the list
set(handles.listbox_labels, 'String', upd_list)     % restore cropped version of label list

% Disable the delete pushbutton if there are no more items
existingItems = get(handles.listbox_labels, 'String')
if(isempty(existingItems))
   handles.btnDeleteLabel.Enable='off'
end

tjvv9vkg

tjvv9vkg2#

只需将单元格方括号替换为普通方括号:

%existingItems{selectedId} = []; % replace this with next line
existingItems(selectedId) = [];

相关问题