2017-06-03 45 views
1

アイテムを動的に追加または削除できるリストボックスを作成しようとしています。
セットアップは次のようになります。
first box is an <code>edit text</code> box to enter a label name, second box is the listbox objectMatlabガイド:リストボックスからアイテムを追加/削除する

を不幸に - 1の写真から見ることができるように - 私は、リストの合計の長さが同じで、代わりのままの要素を削除すると表示されたリストは、今の穴を含むリストを縮小。

誰もこの種の動作を回避する方法を知っていますか?

これは、これまでに削除ボタンのための私のコードです:「空」のエントリを削除する

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

最も単純な方法は、remainigアイテムとlistbox文字列の更新です。

三つの可能性があります。

  • 最初の要素が削除されました:新しいリストは、最後の要素はupd_list={existingItems{2:end}}
  • を削除されています:新しいリストはupd_list={existingItems{1:end-1}}
  • ANS中間要素になりますが、削除されました:新しいリストは

リストのすべての要素が削除されているかどうかを確認することもできますこの場合、「削除」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」

関連する問題