Is it possible to pass a variable throu a callback function?

11 vues (au cours des 30 derniers jours)
Merse Gaspar
Merse Gaspar le 28 Mai 2023
Commenté : Walter Roberson le 28 Mai 2023
My problem is, that I have lots off similar buttons, generated inside a for cycle, and I dont want to write the same number of callback functions. It would suffice if a parameter could be passed to indicate which button is called, i.e. which button calls the function. Example:
for i = 1:100
mybutton(i) = uicontrol('Style','pushbutton','String',sprintf('Nr. %d',i),'Position',[30*i,10,20,20],'BackgroundColor',[.5 .5 .5],'Callback',{@button_Callback});
end

Réponse acceptée

Walter Roberson
Walter Roberson le 28 Mai 2023
However, in the special case of setting up callbacks, when you use the cell syntax like you do in 'Callback',{@button_Callback} then anything you put as additional cell elements will be passed as an additional parameter to the function. So for example if you had 'Callback', {@button_Callback, i} then the value of i as of the time the control is built, would be passed as the third parameter to button_Callback so you could know the button number.
However... even that turns out to be unnecessary. When a callback is invoked, the first thing passed to the callback is the handle to the object that the callback is about. So even with just 'Callback',{@button_Callback} the first parameter passed to button_Callback would be the handle to the uicontrol, same as what would have been stored into mybutton(i) . You can use that to access the uicontrol properties, including the String property, or including any UserData that you might have set when you built the uicontrol.
  2 commentaires
Merse Gaspar
Merse Gaspar le 28 Mai 2023
Thank you very much, this {@button_Callback, i} looks very nice and simple, but how can I extract the value i in the Callback function. How to refer the cell?
Walter Roberson
Walter Roberson le 28 Mai 2023
You would declare
function button_Callback(hObject, event, button_number)
and access button_number inside the callback.
As I indicate though, you do not need to do this as you can access hObject.String or hObject.UserData. For example,
for i = 1:100
mybutton(i) = uicontrol('Style', 'pushbutton', ...
'String', sprintf('Nr. %d',i), ...
'Position', [30*i,10,20,20], ...
'BackgroundColor', [.5 .5 .5], ...
'Callback',@button_Callback, ...
'UserData', i);
end
By the way, would uibuttongroup be suitable for your purposes?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Migrate GUIDE Apps dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by