필터 지우기
필터 지우기

How do I determine whether a UI callback was triggered by a keypress or a mouse click?

조회 수: 7 (최근 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?

채택된 답변

Samay Sagar
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 CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by