Change value of a dropDown menu containing objects of different classes

조회 수: 7 (최근 30일)
Nicolas Kaiser
Nicolas Kaiser 2021년 6월 29일
답변: Animesh 2024년 2월 21일
Hello dear community,
I have implemented various DropDown elements in my Matlab app. One of my DropDown elements have objects of different classes available for selection. However, all objects have the same superclass and inherit the overloaded comparison operator. This operator uses the name, an attribute of the objects, to compare them.
If I change the selected object of the DropDown element, Matlab finds the correct entry in the ItemsData of the DropDown element and does not throw me any errors. But if I now want to change the value of the DropDown element via code and write for example:
app.(name_dropDown).Value = test_object;
I get the error message that test_object is not part of the ItemsData. The problem is apparently that ItemsData is a cellarray, since this contains various objects of various subclasses, and Matlab wants to validate test_object via the ismember function, then ends up in the catch block and uses isequal in combination with cellfun. Apparently, the isequal function does not call the overloaded comparison operator. If this would be called the whole thing would work.
Does anyone have an idea how I can cleverly solve this?
Thanks a lot!

답변 (1개)

Animesh
Animesh 2024년 2월 21일
I understand the challenge you are facing with the “DropDown” elements in MATLAB, with the intricacies of using the overridden comparison operator. I have attempted to replicate a similar setup on my end, and it works fine for me.
We can do something like this to implement a method in the superclass to find the equivalent object in the ”ItemsData” based on the custom comparison logic.
function tf = eq(obj1, obj2)
tf = strcmp(obj1.name, obj2.name);
end
Then we can instantiate objects and set the “DropDown Items” and “ItemsData” in “startupFcn” of the “mlapp
obj1 = SubClassA('Object 1');
obj2 = SubClassB('Object 2');
obj3 = SubClassA('Object 3');
% Set the DropDown Items and ItemsData
app.DropDown.Items = {obj1.name, obj2.name, obj3.name};
app.DropDown.ItemsData = {obj1, obj2, obj3};
Now we can change the value of the DropDown element via code like this:
test_object = SubClassA('Object 1');
app.DropDown.Value = test_object;
However, if ”test_object” is not recognized as part of “ItemsData”, it could mean that the overridden “eq” method isn't being called as expected.

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by