Can you create GUI Elements as an array? (Avoiding eval)

6 ビュー (過去 30 日間)
Davis
Davis 2013 年 3 月 11 日
I'm working on a GUI that someone else started. Currently, we have text elements with tags: Section1OK, Section1Error, etc ... , Section2OK, Section2Error, etc ..., all the way up to 16. Because of this, when I want to work on these elements, my loop has to look something like this:
for i = 1:16 eval(['set(handles.Section',num2str(i),'OK,''Visible'',''off'');']) end
Which is annoying to look at.
Is there a way to rename/reorganize these elements so I can loop through them without using eval?

採用された回答

Walter Roberson
Walter Roberson 2013 年 3 月 11 日
In particular you could use dynamic field names.
Also as long as the handles themselves continue to be valid, you could put them into an array once, save the array away, and then use it as an array:
handles.sectionhandles = [handles.Section1OK, handles.Section1Error, ....];
guidata(hObject, handles);
and then after that,
set(handles.sectionhandles, 'Visible', 'off');

その他の回答 (1 件)

Daniel Shub
Daniel Shub 2013 年 3 月 11 日
You can access fields of structures dynamically. This is very powerful and you can replace
eval(['set(handles.Section',num2str(i),'OK,''Visible'',''off'');'])
with
set(handles.(['Section',num2str(i),'OK']), 'Visible', 'off');
  2 件のコメント
Jan
Jan 2013 年 3 月 11 日
I prefer this equivalent code:
set(handles.(sprintf('Section%dOK', i)), 'Visible', 'off');
Davis
Davis 2013 年 3 月 11 日
Thanks, I appreciate everyone's answers -Davis

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by