Info

This question is closed. Reopen it to edit or answer.

Callback function not seeing App Data

1 view (last 30 days)
Jason Atwood
Jason Atwood on 18 Jul 2012
Closed: MATLAB Answer Bot on 20 Aug 2021
I am trying to pass data to/from a Callback function for my GUI. I am using App Data with setappdata and getappdata. I have looked at the demo and mimicked it precisely. However, the Callback subfunction is not seeing the App Data. Here is a simplified version of my code that demonstrates my problem:
function [] = system_modelling3 ()
clear all
close all
clc
f = figure('Visible','on','Position', [200 200 200 50]); % create figure
system_parameters = struct('initilized',1); % initialize non-empty structure
setappdata(f,'system_parameters',system_parameters) % set App Data
system_parameters.file_vmodel = 'vmodel.m'; % add field to structure
setappdata(f,'system_parameters',system_parameters); % update App Data
fprintf('\n\nMain function sets the App Data as: \n')
output = getappdata(f,'system_parameters') % confirm that App Data updated
% gui controls
selectvmodel = uicontrol(f,'Style','pushbutton','String','Load any file.','Position', [10 10 100 20],'Callback',{@selectvmodel_Callback});
function selectvmodel_Callback(f,eventdata)
temp = getappdata(f,'system_parameters'); % get App Data
temp.newfile_vmodel = uigetfile('*','Load any file.'); % remove extension from file
setappdata(f,'system_parameters',temp) % update App Data
fprintf('\n\nCallback updates App Data as :\n')
output = getappdata(f,'system_parameters') % confirm that App Data updated

Answers (1)

Walter Roberson
Walter Roberson on 18 Jul 2012
In your callback, you getappdata() against f, which is the first parameter of the callback. The first parameter of a uicontrol callback is always the handle of the source of the callback, which is to say the object whose callback it is, the uicontrol. You are attempting to get the appdata of the uicontrol. But the uicontrol does not have any appdata: you attached the appdata to the figure.
Moral of the story: it is probably better to stick to "src" or "hObject" for the name of the first parameter of normal callbacks, to remind yourself that the parameter is being supplied automatically and has no association with any like-named variable in any other routine.
function selectvmodel_Callback(src, eventdata)
f = ancestor(src, 'figure');

Community Treasure Hunt

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

Start Hunting!