How do I determine whether a UI callback was triggered by a keypress or a mouse click?
16 次查看(过去 30 天)
显示 更早的评论
I have a UI table in my app (using App Designer) and when editing data in the table cells, the user can exit the cell (and hence trigger the CellEdit callback) either by hitting the Enter key or by clicking elsewhere with the mouse. In the case where the keypress is used, I would like the focus to move to the cell beneath (in the next row), similar to the typical behavior in a spreadsheet application. In the case where the mouse click is used, I want it to just use the default behavior (focus goes to wherever the user clicked). So I’m assuming I need to know whether the callback was triggered with the keyboard or the mouse, so that I can act accordingly. But I’ve searched the properties of the CellEditData event and can’t find this information anywhere. Does anybody know if it’s possible to get this information? Or is there a better way to achieve the desired behavior?
0 个评论
采纳的回答
Samay Sagar
2024-2-21
Since the “CellEditEvent” data doesn't provide direct information about the input method used to trigger the callback, we can use a workaround by introducing a flag to track the last input method. This flag will be set within a “KeyPressFcn” that listens for the Enter key. When the “CellEditCallback” is invoked, it will check this flag to determine the next action allowing for different behaviours based on the input method.
Here's how you can implement this solution:
Firstly, add a private property to your app class to store the last input method:
properties (Access = private)
LastInputMethod = 'mouse'; % Default to mouse
end
Next, define a “KeyPressFcn” for the table to update this property when the Enter key is pressed
function UITableKeyPress(app, event)
if strcmp(event.Key, 'return')
app.LastInputMethod = 'keyboard';
else
app.LastInputMethod = 'mouse';
end
end
In the “CellEditCallback”, you can then check the LastInputMethod property:
function UITableCellEdit(app, event)
indices = event.Indices;
if strcmp(app.LastInputMethod, 'keyboard')
% Move focus to the cell below if the Enter key was used
nextRow = indices(1) + 1;
if nextRow <= size(app.UITable.Data, 1)
app.UITable.Selection = [nextRow, indices(2)]; % Move focus to the cell below
end
end
% Reset the input method to mouse after processing
app.LastInputMethod = 'mouse';
end
Make sure to assign both the “KeyPressFcn” and the “CellEditCallback” to your table. You can do this in the “startupFcn” of the app
function startupFcn(app)
app.UITable.KeyPressFcn = @app.UITableKeyPress;
app.UITable.CellEditCallback = @app.UITableCellEdit;
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Migrate GUIDE Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!