Redirect keyboard input into LineEdit

Godot Version

4.2.1

Question

Hello, how do I redirect keyboard input to LineEdit from my script _input function?

I would like to process all key presses and redirect some of them to a LineEdit UI element. Here is what I have so far:

func _input(event):
	if event is InputEventKey && event.pressed:
		var should_go_to_ui = detect_should_go_to_ui(event)
		
		if !should_go_to_ui:
			return
		
		if event.unicode != 0:
			var char = OS.get_keycode_string(event.unicode)
			$LineEdit.text += char
		elif event.keycode == KEY_BACKSPACE && text.length() > 0:
			$LineEdit.text = $LineEdit.text.left(text.length() - 1)

So far I couldn’t figure out how to send a key event to my LineEdit, so I tried to hardcode handling some basic input cases. However, it became quickly apparent that this is not the right approach, because OS.get_keycode_string(event.unicode) returns ‘SPACE’ for spacebar, instead on an actual space character. Going further with this approach will cause my code to grow out of control with all the possible scenarios.

Hopefully you can point me to some built-in feature I am missing, that causes the LineEdit to process a KeyInputEvent on demand, so I don’t have to reinvent a text editor myself.

You can handle and event with Viewport.set_input_as_handled()

func _input(event):
	if event is InputEventKey:
		var should_go_to_ui = detect_should_go_to_ui(event)
		
		if !should_go_to_ui:
			get_viewport.set_input_as_handled()

This suggestion gave me an idea to approach my objective from another direction.

My initial hope was to programmatically direct only the desired input to the UI element, but it seems that it’s easier to direct everything to the UI element, and trap the undesired input via set_input_as_handled.

Basically I used the _input function suggested by mrcdk, but I also had to add the code below to the LineEdit to ensure that it always receives all input that isn’t rejected by the criteria of the detect_should_go_to_ui function.

func _ready():
	grab_focus()

I don’t know if this is idiomatically a good way to develop a ui, but it does appear to work.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.