Add `autofocus` property to Control
- Adding
autofocusproperty. The control will attempt to automatically grab focus when it becomes visible. If multiple controls enableautofocusproperty, the last control to become visible will grab focus. - Adding documentation to
autofocusproperty.
Fix https://github.com/godotengine/godot-proposals/issues/6298
To test the behavior, you can use the attached project (autofocus is enabled on two buttons, the last one gets focus when the game starts).
Maybe make it work like focus_on_show? It will be more useful (for example, in popup with text field: text field should be focused every time when popup shows, and there is no sense in recreating popup every time to make current realization work).
@Summersay415 As discussed here, most agreed with autofocus which is consistent with the HTML attribute name.
Summary of the discussion:
- 4 votes for
autofocus - 2 votes for
focus_on_ready - One vote for
show_focused,focus_on_show,grab_focus_on_ready
Make that one more vote for autofocus
as a game dev and creator of game UI’s of 14 years now, i can wholeheartedly say I need autofocus when the node becomes visible; not when it is initialized. it is unclear to whether that’s what this PR does, and I am indifferent to what the variable is called, but that is the functionality I have built for every project time and time again.
example usecase: a panel enables a previously hidden sub-panel, so focus needs to move there.
I implemented autofocus when the control becomes visible, as suggested by @AdriaandeJongh. The accompanying documentation has been updated.
Now all tests have passed successfully.
example usecase: a panel enables a previously hidden sub-panel, so focus needs to move there.
autofocus is not a complete solution for this case, assuming you want the 2 panels to be visible together.
You can move focus to the new panel, but once it closes, you need to somehow focus the previous panel. autofocus does not provide that.
If both panels are visible, you can navigate focus between the panels. Usually you'd want to avoid it, but changing focus mode involves using code (or some convoluted callback binds), at which point you can focus the new Control manually.
Even if you show only one panel, once the sub-panel is closed, you'd want to go back to the button that opened it, not some fixed button that happen to be autofocus. This again involves code.
So unless I'm missing something, autofocus has rather limited usage and realistically it can save a couple lines of code. It does not avoid adding a script, like mentioned in the proposal, because you need code at some point to properly tweak the behavior.