+1 vote

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?

in Engine by (13 points)

2 Answers

0 votes

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

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.

by (58 points)
edited by
+1 vote

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:

by (58 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.