MATLAB: App Designer KeyPress callback for a Tree

app designerMATLAB

Is there a work around for making a KeyPress callback when a Tree is active within the App Designer? I would like to remove selected tree nodes when the user presses delete but there are no keypress callbacks on the Trees. There is a figure wide keypress callback but I dont see a way to determine if the tree is active or one of the edit fields are active.

Best Answer

Chris,
As you mentioned, App Designer Trees do not yet have a KeyPress callback. While the UIFigure does have this callback, there are a few quirks to get around in order to use it in conjunction with the Tree. The user must select the node(s) in the tree and this click somewhere on the figure outside of the Tree and not on the title bar of the figure in order to inactivate, but not deselect the node(s). This will allow the UIFigure's KeyPress callback to active. I used the following code to look for the 'delete' button to be pressed and to delete all selected nodes within the Tree.
% If delete key is pressed, then delete the selected node(s)
if strcmp(event.Key,'delete')
arrayfun(@delete,app.MyTree1.SelectedNodes)
end
This works okay when only a single Tree exists in your UIFigure that you what to apply this ability to, but less so when there are multiple Trees. If you prefer to still use the KeyPress callback to delete nodes on multiple trees, then you could use a dual keypress such as by first selecting and holding aa number key (1 - for 1st tree, 2 - for 2nd tree, etc.) before pressing delete.
% If '1' key is held and then delete key is pressed, then delete the selected node(s) from the 1st tree
if strcmp(event.Modifier,'1') && strcmp(event.Key,'delete')
arrayfun(@delete,app.MyTree1.SelectedNodes)
end
% If '2' key is held and then delete key is pressed, then delete the selected node(s) from the 2nd tree
if strcmp(event.Modifier,'2') && strcmp(event.Key,'delete')
arrayfun(@delete,app.MyTree2.SelectedNodes)
end
% etc..
However, it might be more useful to add a pushbutton near each of your Trees to perfrom this task versus using the KeyPress callback. This would simply the user interface by making it much clear how to delete from which Tree. A pushbutton will also eliminate the need to first select outside of the Tree before the UIFigure callback can be accessed.
Good luck and hope this helps.
-Allen