2
$\begingroup$

How may I add an operator to the Context Menu of a UI List? Context Menu of UI List

Context menus seem to be defined per Spaces (e.g. NODE_MT_context_menu in the below code). Could this be set for the menu of a region? Thank you!

def draw_menu(self, context):
    layout = self.layout
    layout.separator()
    layout.operator("node.duplicate_move", text="My new context menu item")

def register():
    bpy.types.NODE_MT_context_menu.append(draw_menu)

def unregister():
    bpy.types.NODE_MT_context_menu.remove(draw_menu)
$\endgroup$

1 Answer 1

4
$\begingroup$

For a UI list context menu you can use bpy.types.UI_MT_list_item_context_menu. So in your code snippet:

def register():
    bpy.types.UI_MT_list_item_context_menu.append(draw_menu)

def unregister():
    bpy.types.UI_MT_list_item_context_menu.remove(draw_menu)

To figure out the type, I executed this in the Python console and looked for the most plausible one:

blender_types = dir(bpy.types)
for blender_type in blender_types:
    if 'context_menu' in blender_type:
        print(blender_type)

In addition:

What type of list and which list item did the user right-click on? According to the Blender docs you can use context.button_pointer and context.button_prop for that. See the code example in the docs for a dump function of all the properties of button_pointer and button_prop.

As far as I can tell, context.button_pointer.active is the list item the user clicked on.

context.button_prop.name gives an indication which type of list is clicked, e.g. 'Active Shape Key Index' or 'Active Vertex Group Index'. This name is used as title at the top of the context menu:

enter image description here

$\endgroup$
4
  • $\begingroup$ That's waaaaay cleaner than my previous solution! Thank you so much Sietse!!! $\endgroup$ Sep 27 at 19:43
  • $\begingroup$ Oh, one question: how do I know which UI list is right-clicked (when there are many) from that draw menu function? $\endgroup$ Sep 27 at 19:48
  • 1
    $\begingroup$ Yeah, good question. context.button_pointer.active points at the active item in the list. I will update my answer. $\endgroup$ Sep 27 at 22:47
  • $\begingroup$ As an addition not all data containers implement an active member, so the second method might fail. You can get the active item with getattr(context.button_pointer, context.button_prop.identifier) $\endgroup$
    – Gorgious
    Oct 28 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.