2
$\begingroup$

I was wondering if in a UI panel it is possible to capture a keyboard event

I am aware that this can be done in an operator in the invoke function like this:

def invoke(self, context, event):
    if event.type == 'A':
        print("Example A")
    if event.type == 'B':
        print("Example B")

But I would like to do it in a panel, and I don't know if it's possible, in case I would like to clear up any doubts about it, I would like to do something like this:

(My example is incorrect, event.type doesn't exist, but that's for illustration purposes only)

import bpy

class LayoutDemoPanel(bpy.types.Panel):
    """Creates a Panel in the scene context of the properties editor"""
    bl_label = "LayoutDemoPanel"
    bl_idname = "LayoutDemoPanel"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "LayoutDemoPanel"

    def draw(self, context):
        layout = self.layout
        


        # If button 'A' is pressed
        if event.type == 'A':
            self.layout(text="Example A")
        # If button 'B' is pressed
        if event.type == 'B':
            self.layout(text="Example B")


def register():
    bpy.utils.register_class(LayoutDemoPanel)


def unregister():
    bpy.utils.unregister_class(LayoutDemoPanel)


if __name__ == "__main__":
    register()
$\endgroup$
7
  • 1
    $\begingroup$ Hello, UI related methods don't have access to keyboard events, you can either use a modal operator running in the background (I wouldn't advise to do it, it disables auto save feature) or define a keymap item that will trigger an operator and change a property stored somewhere (usually in the scene custom props) to toggle panel behaviour $\endgroup$
    – Gorgious
    Commented Feb 18 at 17:32
  • $\begingroup$ Hello. It might be an interesting idea, but I wouldn't want to cause problems for users with a modal. At the moment the invoke method I mentioned is exactly inside an operator, which by pressing a key does something different $\endgroup$
    – Noob Cat
    Commented Feb 18 at 18:42
  • $\begingroup$ I think you can use a keymap item to directly change a property value without using an operator, however I don't remember the syntax $\endgroup$
    – Gorgious
    Commented Feb 19 at 8:48
  • $\begingroup$ Here it is ! docs.blender.org/manual/en/latest/advanced/… $\endgroup$
    – Gorgious
    Commented Feb 19 at 8:50
  • $\begingroup$ Well it is an operator, but you don't have to define a new one $\endgroup$
    – Gorgious
    Commented Feb 19 at 10:16

0

You must log in to answer this question.

Browse other questions tagged .