What is an accelerator for the PopupMenu node?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zyq0825

Can anyone explain to me what is an accelerator for the PopupMenu node, please?

The document says “Accelerators are special combinations of keys that activate the item, no matter which control is focused.”, but it’s asking for an int, which is the count of the accelerator. Then how do I set the “special combinations of keys”? Is it the same as a shortcut? If so, when I add_shortcut, do I need to set the accelerator as 1 as well?

:bust_in_silhouette: Reply From: sprite-1

I found your question while trying to figure out the answer myself. Apparently, from my trial and error, it seems to work like this.

When you call the add_item method for PopupMenu, the third parameter for shortcut keys is generated by making an InputEvent and passing a value from that to said third parameter.

For example:

# This sets it to "Ctrl + O"
var i := InputEventKey.new()
i.control = true
i.scancode = KEY_O

# It's important to call `get_scancode_with_modifiers()` to convert the value to `int`
$MyPopup.add_item("Open", 0, i.get_scancode_with_modifiers())

Will result in this:

enter image description here

Edit:
I made it a helper function to make things easier to get that int value.

func get_shortcut(keycode:int,modifier:=[]) -> int:
	var i := InputEventKey.new()
	i.control = modifier.has("ctrl")
	i.shift = modifier.has("shift")
	i.alt = modifier.has("alt")
	i.scancode = keycode
	return i.get_scancode_with_modifiers()

To use it, just do something like get_shortcut(KEY_O,["ctrl"]) = Ctrl+O
For multiple modifiers, just do get_shortcut(KEY_DELETE,["ctrl","shift"]) = Ctrl+Shift+Del.

:bust_in_silhouette: Reply From: Epidal

You actually don’t need to use InputEventKey like sprite-1 suggested. If you look at the get_scancode_with_modifers code, you can see it just OR’s the key scancode with a mask for the modifers (KEY_MASK_CTRL, KEY_MASK_SHIFT, KEY_MASK_ALT, and KEY_MASK_META).

Creating an accelerator for a key combination like ctrl+shift+s, for example, is as simple as using:

KEY_S | KEY_MASK_CTRL | KEY_MASK_SHIFT