2017-06-03 97 views
1

我想創建一個列表框,我可以動態地添加或刪除項目。
的設置是這樣的:
first box is an <code>edit text</code> box to enter a label name, second box is the listbox objectMatlab指南:添加/刪除列表框中的項目

不幸的是 - 作爲一個從圖片中可以看到 - 當我刪除元素列表的總長度保持不變,而不是和收縮列表中顯示的列表現在包含孔。

有誰知道如何避免這種行爲?

這是我的刪除按鈕的代碼至今:

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 

回答

2

刪除「空」項中的simpliest辦法就是更新listbox字符串與remainig項目。

有三種可能性:

  • 的第一個元素已被刪除:新的名單將在upd_list={existingItems{2:end}}
  • 的最後一個元素已被刪除:新的名單將在upd_list={existingItems{1:end-1}}
  • ANS中間元件已被刪除:新的名單將在upd_list={existingItems{1:selectedId-1} existingItems{selectedId+1:end}}

您還可以檢查列表的所有元素都被刪除,在這種情況下,禁用「刪除」pushbutton;在這種情況下,您必須在「添加」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 ites 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 

enter image description here

希望這有助於

Qapla」