Deleted passed UIFigure handle on bootup of MATLABWindow
6 views (last 30 days)
Show older comments
When running the following script, on the first bootup of MATLABWindow for the uifigure, sometimes the figure handle will be deleted before it can be used: the script will show "handle to deleted Figure". Moving the mouse over the window activates the error.
It doesn't happen everytime. I have found the most reliable way to produce this result is to run the script, quit out of MATLABWindow, clear the variables, and run it again.
What is going on? Is this a bug? How could I avoid it? (I want to preserve the callbacks, something about the persistence, and the one-time initialization of S. This script is a very pared down version of a more complete tool.)
clear S
S.fig= uifigure;
set(S.fig,'WindowButtonMotionFcn',{@Callback, S})
function Callback(~,~, s)
persistent S
if isempty(S)
S= s;
end
S.fig
end
1 Comment
Jan
on 18 Apr 2022
What does this mean: " on the first bootup of MATLABWindow for the uifigure"?
Please post the complete error message, which shows, in which line the problem occurs.
Accepted Answer
Jan
on 18 Apr 2022
If you run this script twice, the persistent variable S contains the handle of the former figure.
Workaround:
clear S
S.fig = uifigure;
set(S.fig,'WindowButtonMotionFcn', {@Callback, S})
function Callback(~, ~, s)
persistent S
if isempty(S) || ~isequal(S, s)
% ^^^^^^^^^^^^^^^^^ Replace formerly stored figure handle
S = s;
end
S.fig
end
Or start with clearing the callback also:
clear S
clear Callback
This resets the persistent variable.
Storing the figure handle persistently in a callback function seems to be a bad idea. The figure handle is the first input of the WindowButtonMotionFcn in every case. Performing some setup in the first call should not be hidden in this callback, but in a code block for initialising the function. If you want to know, if a figure was setup up before, use a flag in the figure's UserData or ApplicationData instead of a persistent variable in the callback. Then you get no confusion between mutliple instances of the figure.
More Answers (0)
See Also
Categories
Find more on Develop uifigure-Based Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!