Clear Filters
Clear Filters

Set class method as CloseRequestFcn

7 views (last 30 days)
I am currently working on a waitbar that is implemented as a class. I need to detect when the user clicks the X-button of the window to cancel computations and then set a flag.
Considering the following class:
classdef myWaitbar < handle
properties
figHandle
cancel
end
methods
function obj = myWaitbar()
obj.cancel = false;
obj.figHandle = figure('CloseRequestFcn', @...);
end
function setFlag(obj)
obj.cancel = true;
end
end
end
Does anybody know how to declare CloseRequestFcn and setFlag to make this work? I tried a few different approaches but could not find a proper way.
Thank you

Accepted Answer

Geoff Hayes
Geoff Hayes on 3 Feb 2017
Sebastian - you can try the following
function obj = myWaitbar()
obj.cancel = false;
obj.figHandle = figure('CloseRequestFcn', @(h,e)obj.setFlag);
end
function setFlag(hObject,eventdata)
hObject.cancel = true;
delete(hObject.figHandle);
end
The setFlag method will be called when the x is pressed in the corner of the wait bar figure. (At least it does for me when using R2014a.) I'm not sure how you will report the change to cancel though. Do you have "something" listening or waiting for it to change value?
  2 Comments
Guillaume
Guillaume on 4 Feb 2017
Edited: Guillaume on 4 Feb 2017
Hum, I believe the anonymous function should be:
@(h,e) obj.setFlag(e)
%or
@(~, e) obj.setFlag(e)
As it is you'll get a not enough input arguments error in setFlag.
And I find calling hObject the first argument of setFlag misleading as it seems to implies it's the h of the @(h,e) whereas it's actually the obj of obj.setFlag, so I'd have:
function setFlag(obj, eventdata)
obj.cancel = true;
delete(obj.fighandle);
end
Or to make everything even clearer:
function obj = myWaitbar()
obj.cancel = false;
obj.figHandle = figure('CloseRequestFcn', @(h,e)obj.setFlag(h, e));
end
function setFlag(obj, hsource, eventdata) %eventdata could be replaced by ~
obj.cancel = true;
delete(hsource);
end
Third option is:
function obj = myWaitbar()
obj.cancel = false;
obj.figHandle = figure('CloseRequestFcn', @(~,~)obj.setFlag);
end
function setFlag(obj)
obj.cancel = true;
delete(obj.figHandle);
end
Sebastian
Sebastian on 4 Feb 2017
Geoff Hayes and Guillaume, thank you for your efforts. I kept trying and finally found a solution that works for me in R2016b:
...
obj.figHandle = figure('CloseRequestFcn', @obj.figureCloseFcn);
...
function figureCloseFcn( obj, src, evt )
...
I am not really sure why this works but I think that src and evt are passed by default to a CloseRequestFcn so it is redundant to add them to the function handle or it even causes errors. I listen for cancel in the main loop to open a questdlg.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming 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!