How do I ignore double clicks in my GUI buttons?
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 4 Jan 2017
Modifié(e) : MathWorks Support Team
le 5 Mar 2021
I have created a GUI containing a button that performs a callback. Sometimes, users accidentally double-click the button, causing the callback to fire twice. How do I stop that?
Réponse acceptée
MathWorks Support Team
le 5 Mar 2021
Modifié(e) : MathWorks Support Team
le 5 Mar 2021
MATLAB UI buttons do not offer support for double-clicking. However, you can implement a mechanism that ignores the second click.
As an example, here is a function that implements such a mechanism. This function makes use of a persistent variable, "check", to count the number of recent clicks. If there are no recent clicks, then the single-click action is executed. However, if there are recent clicks, new clicks are ignored for a short period of time.
function pushbutton1_Callback(hObject, eventdata, handles)
persistent check % Shared with all calls of pushbutton1_Callback.
delay = 0.5; % Delay in seconds.
% Count number of clicks. If there are no recent clicks, execute the single
% click action. If there is a recent click, ignore new clicks.
if isempty(check)
check = 1;
disp('Single click action')
else
check = [];
pause(delay)
end
end
The trick here is to define "check" as a persistent variable, which means that its value doesn't get cleared after the function has stopped executing, but it persists through all calls to this function. This makes it possible to track the number of (recent) calls to this function, effectively identifying double clicks.
You can find more examples on how persistent variables work in MATLAB in the following documentation page:
1 commentaire
Allen
le 21 Fév 2018
I have used the method provided by the MathWorks Support Team and still have the code for my pushbutton GUI execute each time on a multi-click by the user. However, a slight edit to their code does the trick. See example below:
function pushbutton1_Callback(hObject, eventdata, handles)
persistent check % Shared with all calls of pushbutton1_Callback.
% Count number of clicks. If there are no recent clicks, execute the single
% click action. If there is a recent click, ignore new clicks.
if isempty(check)
check = 1;
disp('Single click action')
else
% Ends Callback execution if pushbutton is clicked again before
% Callback has completed.
return
end
% -----Callback function code----- %
% Resets the 'check' variable for additional use of the Callback function
check = [];
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Interactive Control and Callbacks 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!