필터 지우기
필터 지우기

How to select only two items from the list box?

조회 수: 5 (최근 30일)
Michael
Michael 2011년 1월 15일
댓글: Joe S 2019년 10월 24일
I want to select only two items from a list box. The list box should not accept more than two selected items.
Please provide an example for this.

채택된 답변

Matthew Simoneau
Matthew Simoneau 2011년 1월 20일
You can accomplish this by reacting to the selection with a callback and removing the new selection if there are too many.
Create a callback function like this one:
function twoOnly(h,~)
oldValues = get(h,'UserData');
newValues = get(h,'Value');
if numel(newValues) > 2
newValues = oldValues;
end
set(h,'Value',newValues)
set(h,'UserData',newValues)
end
Here's an example of how to use it:
close all;
u = uicontrol( ...
'style','listbox','Max',2,'Position',[10 10 100 100], ...
'String',{'one','two','three','four','five'}, ...
'Callback',@twoOnly)
Note that the 'Max' property with a value of "2" has nothing to do with the limit of two selections. For more information, see the uicontrol reference page.
  댓글 수: 1
Joe S
Joe S 2019년 10월 24일
Works great, tested using both the CTRL and SHIFT button multl-select. Note: If using GUIDE for a GUI, you'll likely need to change "h" to "hObject" and remove "function twoOnly(h,~)"

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 1월 20일
There is no (documented) MATLAB mechanism for restricting the number of multi-selected items in a listbox. Your callback function will need to detect the situation and decide what to do, such as setting the Value property to only reflect the first (or last) two of the chosen values, or popping up an error dialog.

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by