Clearing object from base workspace on closing a GUI

8 views (last 30 days)
I'm buidling a GUI with the following structure:
classdef App < handle
properties
gui
other_properties
end
methods
function obj = App()
% Initialize window
obj.gui = obj.main_window_layout('reuse');
% Assign callbacks
obj.assign_callbacks();
end
end
end
The main windows layout is defined in:
function h1 = main_window_layout(obj,policy)
%% policy - create a new figure or use a singleton. 'new' or 'reuse'.
persistent hsingleton;
if strcmpi(policy, 'reuse') & ishandle(hsingleton)
h1 = hsingleton;
return;
end
%% Create the figure instance
% Define position [x bottom left, y bottom left, width, height]
figure_position = [10 10 112 32.3076923076923];
h1 = figure(...
'PaperUnits','inches',...
'Units','characters',...
'Position',figure_position);
%% Additional uicontrols etc..
end
I'd like the GUI to close when I press the close button in the window, that's why I defined the following callback:
function assign_callbacks(obj)
%assign_callbacks Assigns the callbacks of the GUI
% Closing event
obj.gui_handles.figure.CloseRequestFcn = @(hObject,eventdata)close_figure_Callback(hObject,eventdata,obj);
%% --- Executes on close figure
function close_figure_Callback(~,~,obj)
delete(obj)
delete(gcf)
end
end
I start the GUI by:
%% Only start the app if it is not running yet
if exist('app_object','var') == 0
app_object = App();
else
clear app_object
app_object = App();
end
When I close the figure, the window closes and the GUI is cleared. However, the app_object is still existing in the base workspace, it is empty though. I'd like to clear the object from the base workspace. The reason for this is that I want to prevent my GUI from initializing twice by calling the start script.. Is this the right way to achieve this?

Answers (1)

Walter Roberson
Walter Roberson on 26 Jun 2020
function close_figure_Callback(~,~,obj)
delete(obj)
delete(gcf)
clear main_window_layout %get rid of the persistent
evalin('base', 'clear app_object;');
end
  5 Comments
Walter Roberson
Walter Roberson on 26 Jun 2020
%% Only start the app if it is not running yet
if ~exist('app_object','var') || ~isvalid(app_object)
app_object = App();
else
clear app_object
app_object = App();
end
Mind you, I do not understand why you clear app_object and start a new one if the existing one is still valid ??
Jan Loof
Jan Loof on 26 Jun 2020
Because this re-initializes the app and adds default values to possibly already present values.

Sign in to comment.

Categories

Find more on Code Execution in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!