In Blender, we can add custom items to any context menu, called by pressing the right mouse button, to quickly execute the necessary operators.
Let’s add a new item to the context 3D viewport menu.
First we need to define an operator that we will call through a new item added to the context menu.
1 2 3 4 5 6 7 8 9 |
class TEST_OT_material_init(bpy.types.Operator): bl_idname = 'test.material_init' bl_label = 'Material Init' def execute(self, context): if bpy.context.object: bpy.ops.material.new() bpy.context.object.active_material = bpy.data.materials[-1] return {'FINISHED'} |
In the execute function, we create a new material using the material.new() system operator and assign this material (the last in the list of all bpy.data.materials) to the active object.
Register our operator class in the Blender Python API:
1 |
bpy.utils.register_class(TEST_OT_material_init) |
Next, to draw a new item in the context menu, we need to define a function that will associate the menu item with our operator, and will draw this item.
1 2 3 |
def menu_item_draw_func(self, context): self.layout.separator() self.layout.operator('test.material_init', icon='MATERIAL') |
This function is similar in structure to any draw function in the UI panel’s classes.
In our function, we add a separator to the menu layout, and our operator, specifying its bl_idnamei identifier value in the first parameter of the operator() function.
It remains to add a call to draw our function to the 3D viewport context menu.
1 |
3D viewport context menu class is: VIEW3D_MT_object_context_menu. |
We can add our function to this class using the append command:
1 |
bpy.types.VIEW3D_MT_object_context_menu.append(menu_item_draw_func) |
Now the context menu of the 3D viewport has a new item ‘Material Init’
By selecting which, we will create a new material and assign it to the active object.
New items can be added to the context menu both at the end and at the beginning of it. To add an item to the top of the context menu, we need to use the prepend function instead of the append function:
1 |
bpy.types.VIEW3D_MT_object_context_menu.prepend(menu_item_draw_func) |