Adding an Operator to the Context Menu of a UIList

You can override the context menus for buttons and ui list items.
See Add Operator to Right Click Menu for Operators - #2 by iceythe

Here’s an example that adds a label to the context menu when a vertex group is right clicked.

import bpy


class WM_MT_button_context(bpy.types.Menu):
    bl_label = ""
    # Leave empty for compatibility.
    def draw(self, context): pass


# Your draw function.
def draw(self, context):
    if hasattr(context, "button_pointer"):
        print("Clicked: ", context.button_pointer)

        if isinstance(context.button_pointer, bpy.types.VertexGroups):
            layout = self.layout
            layout.label(text="I'm in vertex groups context menu!")

    if hasattr(context, "button_prop"):
        print("Property:", context.button_prop.identifier)

    if hasattr(context, "ui_list") and context.ui_list is not None:
        print("UI List: ", context.ui_list.bl_idname)


if __name__ == "__main__":
    # Register menu only if it doesn't already exist.
    rcmenu = getattr(bpy.types, "WM_MT_button_context", None)
    if rcmenu is None:
        bpy.utils.register_class(WM_MT_button_context)
        rcmenu = WM_MT_button_context

    # Retrieve a python list for inserting draw functions.
    draw_funcs = rcmenu._dyn_ui_initialize()
    draw_funcs.append(draw)

3 Likes