Dynamically adding callback functionalities to uimenu items

조회 수: 10(최근 30일)
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);
writecell({fichier Fullfilename}, tempfile, 'WriteMode', 'append');
data = readcell(tempfile, 'FileType', 'SpreadSheet');
[C,ia,~] = unique(data(:,2), 'stable');
if numel(ia) > 5
maxLimit = 5;
maxLimit = numel(ia);
for i = 1 : maxLimit
tmp = uimenu(app.OpenrecentlyaccessedfileMenu, 'Text', char(C(i)), 'MenuSelectedFcn', @MenuSelected);
function MenuSelected(src,event)
% Execute this for each file
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
Rik 2021년 5월 17일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Geoff Hayes
Geoff Hayes 2021년 5월 17일
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);
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
Again, I haven't tested this but it might* work.
  댓글 수: 1
Shreedhar Savant Todkar
Shreedhar Savant Todkar 2021년 5월 17일
You're absolutely right, it works. Works like a charm!

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by