classdef delete function and figure CloseRequestFcn mixing problem

5 visualizaciones (últimos 30 días)
Hello I was trying to build some special class that administrate a figure. I wannt that the figure gets closed only if the class object get deleted ! I have tryed the following :
classdef testclass < handle
properties
thefig
end
methods
%constructor generates a new figure
function obj = testclass()
obj.thefig = figure('CloseRequestFcn',@(src,evt) (disp('not allowed')));
end
%when I use clear the destructor isn t called anymore ?!?
function delete(obj)
disp('closing figure');
if ishandle(obj.thefig)
delete(obj.thefig)
end
end
end
end
And then I do the following:
a = testclass
clear a
And here the class destructor didn t get called. What did I do wrong ?
  3 comentarios
Alessandro
Alessandro el 6 de Mzo. de 2013
I have sometime many figures open, and the simple closing of the figure makes the class object illegal. But you are right I still could close the figure over delete(gcf)
per isakson
per isakson el 6 de Mzo. de 2013
You can wrap handle graphic object in handle classes and make it work according to your original intention. The key is to keep 100% control over the references to your instances of the wrappers.

Iniciar sesión para comentar.

Respuestas (1)

per isakson
per isakson el 6 de Mzo. de 2013
Editada: per isakson el 6 de Mzo. de 2013
Two figures are created in the constructor. The first value of obj.thefig is overwritten. I guess, you already found out that with only the first figure the class behaves as you expect. Comment out the second call to figure to verify.
The problem is with the anonymous function
@(src,evt) (disp('not allowed'))
Documentation says:
Object Scope and Anonymous Functions
Anonymous functions take a snapshot of the argument values when you define the
function handle. You must, therefore, consider this scoping when assigning the
Callback property. [...]
and
clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace.
and
[...]MATLAB calls the delete method of any handle object (if it exists) when
the object is destroyed. h is a scalar handle object.[...]
Thus, (it is a bit tricky to find all the relevant information) the method delete is called when the last handle (/reference) to the object is destroyed. The reason the method is not called in your example is that there is still a reference to the object in the anonymous function, which is attached to the figure.
To make the class behave as you expect, change the value of CloseRequestFcn of the figure:
obj.thefig = figure( 'CloseRequestFcn', 'disp(''not allowed'')' );
To remove the figure and the object from memory by brute force:
delete( gcf )

Categorías

Más información sobre Graphics Object Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by