2015-09-15 2 views
0

Я отчаянно пытаюсь создать окно для моего графического интерфейса. Что я хотел бы сделать для начала, написать текст в списке после нажатия кнопки PUSH. Функция обратного вызова из нажимной кнопки:Как добавить элементы в список через графический интерфейс пользователя

function run__Callback(hObject, eventdata, handles) 

    initial_name=cellstr(get(handles.logbox1,'String')) 
    handles.names={'test','haus', 'top', 'down', 'optimistic'} 
    handles.names{end,end}=[]         %Add Element for new text 
    handles.names{end,end}='neuuu'        %Add Element 
    num_element=length(handles.names)       %Count Elements 
    set(handles.logbox1,'String',handles.names)     %Aktualisiere Liste 

    set(handles.logbox1,'Top',num_element)      %Set Listbox to the last Element 

и ListBox находится в том же графическом интерфейсе. Тем не менее, есть ошибка:

rror с использованием hg.uicontrol/комплект

The name 'Top' is not an accessible property for an instance of class 'uicontrol'. 

Может кто-нибудь помочь мне, пожалуйста, я не понимаю, что случилось?

С наилучшими пожеланиями, Джон

+0

Что такое "logbox1"? –

+0

Не понимаю. Вы хотите добавлять новые элементы в список при каждом нажатии кнопки? –

+0

logbox1 ist тег в список, извините за эту путаницу. Его название похоже на то, что он должен регистрировать все шаги, выполненные в графическом интерфейсе. Каждый раз, когда я нажимаю кнопку в GUI или его SUBGUI, я бы хотел увидеть действие в лог-блоке ..... поэтому добавьте элемент с текстовой строкой в ​​лог-файл и сделайте фокус журнала в последнем элементе! но я получаю эту ошибку, когда я пытаюсь правильно настроить фокус, и я не знаю, как получить доступ к журналу из других Callbacks и установить его значение ... был бы рад за вашу помощь! С наилучшими пожеланиями, Джон – john

ответ

1

Вы получили ошибку, потому что Top не property из listbox uicontrol; кроме того, Top не является собственностью ни одного uicontrol.

Вы можете найти here the list of uicontrol properties.

Наиболее ListBox свойство близко к "Top" является ListboxTop.

Я создал два простых графических интерфейса, которые могут помочь вам управлять доступом к списку.

"add_to_listbox" Main GUI содержит:

  • listbox с tag listbox1
  • pushbutton с tag pushbutton1, String "Add Action": каждый раз, когда пользователь нажимает ее, строку, такие как " Основной графический интерфейс: Поставлен строка #x»добавляется сверху ListBox („х“является контер)
  • pushbutton с tag„open_subgui“, String„открыть SubGUI“, чтобы открыть второй графический интерфейс

SubGUI ("add_to_listbox_subgui") содержит

  • pushbutton с tag pushbutton1, String "Добавить действие на главном графическом интерфейсе": каждый раз, когда пользователь нажимает ее, строку, например, «GUI вставленные строки SUB #x»добавляется в верхней части ListBox Основной GUI („х“является контер)

SubGUI обрабатывает добавление строк в ListBox Главная GUI с помощью основного графического интерфейса пользователя listbox handle, который хранится в главном GUI guidata (когда SubGUI открывается Главным графическим интерфейсом, он принимает в качестве входных данных handle в Основной графический интерфейс; через него доступ SubGUI к главному графическому интерфейсу guidata).

В дальнейшем вы можете найти:

  • Main GUI OpeningFcn, в котором «счетчик действия» в инициализирован
  • Main GUI pushbutton1_Callback, который добавляет строку в ListBox каждый раз, когда pushbutton нажатии
  • Главный GUI open_subgui_Callback который открывает SubGUI
  • SubGUI OpeningFcn, в которых оба SubGUI и главный GUI guidata обрабатываются
  • SubGUI pushbutton1_Callback, который добавляет строку в ListBox Main GUI каждый раз pushbutton нажимается

Главная GUI OpeningFcn

% --- Executes just before add_to_listbox is made visible. 
function add_to_listbox_OpeningFcn(hObject, eventdata, handles, varargin) 
% This function has no output args, see OutputFcn. 
% hObject handle to figure 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 
% varargin command line arguments to add_to_listbox (see VARARGIN) 

% Choose default command line output for add_to_listbox 
handles.output = hObject; 

% Update handles structure 
guidata(hObject, handles); 

% UIWAIT makes add_to_listbox wait for user response (see UIRESUME) 
% uiwait(handles.figure1); 
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% 
% Get Main GUI guidata 
gui_data=guidata(gcf); 
% Add (and initialize) button action counter to Main GUI guidata 
gui_data.btn_action=0; 
% Set Main GUI guidata 
guidata(gcf,gui_data); 
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% 

Главная GUI pushbutton1_Callback

% --- Executes on button press in pushbutton1. 
function pushbutton1_Callback(hObject, eventdata, handles) 
% hObject handle to pushbutton1 (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% 
% Add button action (from Main GUI) string to the listbox 
% 
% Get Mani GUI guidata 
gui_data=guidata(gcf); 
% Increment button action counter 
gui_data.btn_action=gui_data.btn_action+1; 
% Set Main GUI guidata (to store button action counter) 
guidata(gcf,gui_data); 
% Generate action string and add it to the listbox 
% The firt strimg is directly add to the listbox 
if(gui_data.btn_action == 1) 
    new_str='Main GUI: Inserted string #1'; 
    set(handles.listbox1,'string',new_str); 
else 
    new_str=['Main GUI: Inserted string #' num2str(gui_data.btn_action)]; 
    % The fisrt string in the list box is returned as "string", to add the 
    % second one, it has has to be first converted into a cellarray 
    if(gui_data.btn_action == 2) 
     tmp_str=cellstr(get(handles.listbox1,'string')); 
    else 
     % The order of the string in the listbox is reversed to have the last 
     % one on top 
     tmp_str=flipud(get(handles.listbox1,'string')); 
    end 
    % Set the updated set of seting to the listbox 
    tmp_str{end+1,1}=new_str; 
    set(handles.listbox1,'string',flipud(tmp_str)); 
end 

Главная GUI open_subgui_Callback

% --- Executes on button press in open_subgui. 
function open_subgui_Callback(hObject, eventdata, handles) 
% hObject handle to open_subgui (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% 
% Open the Sub GUI; the handle of the Main GUI is passed as argument to 
% This allows Sub GUI accessing to the Main GUI guidata 
add_to_listbox_subgui(gcf) 
% Disable the "Open Sub GUI" button 
set(handles.open_subgui,'enable','off') 

SubGUI OpeningFcn

% --- Executes on button press in pushbutton1. 
function pushbutton1_Callback(hObject, eventdata, handles) 
% hObject handle to pushbutton1 (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 

% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
% 
% Add Sub GUI button action string to Main GUI listbox 
% 
% Get Sub GUI guidata 
gui_data=guidata(gcf); 
% Get Main GUI guidata, "gui_data.main_gui" holds the Main GUI handle 
gui_data.main_gui_data=guidata(gui_data.main_gui); 
% Increment the button action counter 
gui_data.btn_action=gui_data.main_gui_data.btn_action+1; 
% Update Main GUI button actin counter 
main_gui_data=guidata(gui_data.main_gui); 
main_gui_data.btn_action=gui_data.btn_action; 
% Store Sub GUI guidata 
guidata(gcf,gui_data); 
% Store Main GUI guidata 
guidata(gui_data.main_gui,main_gui_data); 
% 
% Add button action (from Main GUI) string to the listbox 
% 
if(gui_data.btn_action == 1) 
    % Generate action string and add it to the Main GUI listbox 
    % The firt strimg is directly add to the listbox 
    new_str='SUB GUI Inserted string #1'; 
    set(gui_data.listbox,'string',new_str); 
else 
    new_str=['SUB GUI Inserted string #' num2str(gui_data.btn_action)]; 
    % The fisrt string in the list box is returned as "string", to add the 
    % second one, it has has to be first converted into a cellarray 
    if(gui_data.btn_action == 2) 
     tmp_str=cellstr(get(gui_data.listbox,'string')); 
    else 
     % The order of the string in the listbox is reversed to have the last 
     % one on top 
     tmp_str=flipud(get(gui_data.listbox,'string')); 
    end 
    % Set the updated set of seting to the listbox 
    tmp_str{end+1,1}=new_str; 
    set(gui_data.listbox,'string',flipud(tmp_str)); 
end 

enter image description here

Надеется, что это помогает.

+0

Спасибо, ооочень! – john

+0

Добро пожаловать! Счастлив, что я тебе полезен. Возможно, вы захотите принять ответ, чтобы закрыть вопрос :-) –