Why is a LineEdit not accepting my simulated key press?

Godot Version

4.6.2

Question

I’m trying to create a virtual keyboard. While what I designed seems to work for the _unhandled_key_event() hierarchy, the Components that come with Godot seem to ignore them. For example, I created this simplified version of my virtual keyboard:

extends Control

@onready var line_edit:LineEdit = %LineEdit

var keycode := KEY_A

func _on_click_panel_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.is_pressed():
			var key_event:InputEventKey = InputEventKey.new()
			key_event.keycode = keycode
			key_event.pressed = true
			Input.parse_input_event(key_event)

If I run and click on the pink square, the _on_click_panel_gui_input() method is called and the virtual event is passed to Input. I would have expected the line_edit to then receive the event and add an A to the text. But this doesn’t happen, even if the LineEdit is selected before I click and typing on my physical keyboard does enter letters into my line edit.

Is there a way to get my click on the pink ControlPanel to simulate pressing the A key for the LineEdit?

Maybe do a focus grab first.

E g. $LineEdit.grab_focus()

Before sending keystroke.

That was an interesting issue. I tested around and it seems like you need to set a unicode, not the keycode parameter of the InputEventKey for this to work.

Something like this should work for you:

extends Control

@onready var line_edit:LineEdit = %LineEdit

#var keycode := KEY_A

func _on_click_panel_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.is_pressed():
			var key_event:InputEventKey = InputEventKey.new()
			#key_event.keycode = keycode
			key_event.unicode = "a".unicode_at(0)
			key_event.pressed = true
			Input.parse_input_event(key_event)

Just came to the same conclusion… you posted your answer while I was writing my answer.

Sorry, Godot Forum is a competitive place, you need to be swift :wink:
Glad you came to the same conclusion though