I’d like to create a small panel in the viewport UI with ‘button’ Operators that when pressed mimic keyboard input. For example, how would I execute something like ‘NUMPAD_0’ being pressed? Think of it like an on-screen keyboard.
I specifically don’t want to create a modal operator, as I don’t want anything to run in the background waiting for a keypress that then checks what key was pressed etc. I just want to simply execute the corresponding key when the button is pressed in the panel.
Code-wise I’m just asking for the one-liner that gets me the keypress. All of the rest with regards to panels, operators, etc. I know how to do all that. I just don’t know the Blender namespaces how to reference the keys.
If what you want is just to have a button that acts like a shortcut, then you don’t need to simulate the key press… Just look at the operator for that key (in the preferences::keymap) and create a button that calls that operator:
# 3DView::ObjectMode::ObjectMode(Global):: X Key >> calls "object.delete"
#in the panel drawing call:
layout.operator("object.delete")
The only difficulty in this, is if the context is not the correct one for the operator (i.e. calling “object.delete” from a panel in the “TextEditor”)
I’d like to have the correct behaviour automatically inferred based on the context. As a workaround, I could do what you suggest with the added step of manually checking the context first and then calling the appropriate command.
It’s (very) important that you check your context before you try to do anything!! That’s the main purpose of the poll() function.
When calling operators, this is allways checked by the operator itself. What might happen is that your operator requires something in its context that is not available in the context of your panel… for example, the grab function in most editors only work within the editor, and with the elements from that editor; but you can still move an object from any other editor, as long your operator knows how to find them.
It’s also possible to highjack some operators (at least the ones written in python), thought most of the times you can directly replicate their function yourself (within your own context).
My code already does check to make sure that my operators are called in the correct context, but I have those checks as part of the overall script rather than segment them into poll() and execute(). I use init.py only to set up my UI elements, not do any checks. Once an operator is clicked, I ‘return SomeScriptFile.someMethod(self)’ and do all my context checking there via ‘self’. This way everything is self-contained and logic isn’t split between multiple files (apart from lib-based method calls).
Hi, did you find a solution? I was just googling this.
I am doing some automated testing on my addon, and would love to simulate keystrokes.
Besides that, it would allow me to do a lot of other crazy stuff that isn’t by now possible in the AP