MATLAB Answers

Dynamically adding callback functionalities to uimenu items

5 views (last 30 days)
EDIT:
Following the suggestions to my question here, I was able to create a temporary file that stores the recently accessed files (here is the code):
function myRecentlyAccessedFiles(app, Fullfilename)
[~, name, ext] = fileparts(Fullfilename);
fichier = [name ext]; % creates the filename with extension
tempfile = 'temp.xlsx';
if ~exist(tempfile, 'file')
uimenu(app.OpenrecentlyaccessedfileMenu, 'Text', '< No files >');
writecell({''}, tempfile);
return;
else
writecell({fichier Fullfilename}, tempfile, 'WriteMode', 'append');
data = readcell(tempfile, 'FileType', 'SpreadSheet');
[C,ia,~] = unique(data(:,2), 'stable');
if numel(ia) > 5
maxLimit = 5;
else
maxLimit = numel(ia);
end
for i = 1 : maxLimit
tmp = uimenu(app.OpenrecentlyaccessedfileMenu, 'Text', char(C(i)), 'MenuSelectedFcn', @MenuSelected);
end
end
function MenuSelected(src,event)
% Execute this for each file
end
end
By doing so, after each iteration, the "Open recently accessed file" menu gave me the proper list (screensot below)
I need to open the file that is selected from the sub-menu of the "Open recently accessed file".
However, when I execute this, irrespective of the file chosen, the code always executes the last file in the list.
Am I doing something wrong here?
  3 Comments
Rik
Rik on 17 May 2021
You can replace getappdata and setappdata with a hidden property of your app. All Matlab functions will have access to the groot object, so storing it there is a bad idea in general.
Wouldn't it be the best solution to store these names in a cell vector? By using a property the callback using the file can easily add the current file to the list, removing the oldest if the number of elements exceeds the max count or reordering if the file is already in the list.

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 17 May 2021
Shreedhar - in your loop, the variable tmp is always being overwritten
for i = 1 : maxLimit
tmp = uimenu(app.OpenrecentlyaccessedfileMenu, 'Text', char(C(i)), 'MenuSelectedFcn', @MenuSelected);
end
so this local variable will always refer to the last created menu item. I haven't tested this, but since your callback signature is
function MenuSelected(src,event)
then the src input parameter should correspond to the menu item object that was selected. In that case, you might be able to change your code to
function MenuSelected(src,event)
setappdata(0, 'accessByMainWindow', 'False');
setappdata(0, 'recentFile', src.Text); % <---- use src if possible
BrowseWindow_optimized_App(); % <-- This function simply loads my file
end
Again, I haven't tested this but it might* work.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by