How can I add my operator to existing right-click (context menu) in the shader editor?
3 Answers
The Shader Editor context menu is called NODE_MT_context_menu
(found by inspecting Preferences> Keymap> Node Editor and looking for Right Mouse) and we can 'append
' (add) a draw function, which draws your menu item, into the existing menu. In the example below I have used the Node Editor's existing 'Duplicate' operator.
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)
Explanation:
- The
draw_menu
function deals with the UI that you want to add to the context menu (anoperator
) by using thebl_idname
of your operator - in this casenode.duplicate_move
. - The
register
function should contain, in addition to the code that registers your operator, the code toappend
that UI into the existing menu. - In the case of an add-on, the
unregister
function will remove the UI you added.
Note:
- The
separator()
line is not required, but useful for keeping your UI separate from the existing one. prepend
can be used instead ofappend
to add items to the top of the menu instead of the bottom.
Some more information about menus can be found in the 2.80 Python API documentation. A few examples of extending the existing UI can be found in the Python templates included with Blender via the Templates menu in the Text Editor header.
Ray's excellent answer and explanation still hold true for Blender 3.x
and current the API. These also helped me with adding menu items:
For anyone who came here looking for the context menu for mesh editing mode, the keyword is VIEW3D_MT_edit_mesh_context_menu
so the code would be
def register():
bpy.types.NODE_MT_context_menu.append(draw_menu)
Which is the menu that appears when you right-click (by default) in Edit Mode. For some reason, I couldn't find it in the Blender API reference.
https://blender.community/c/rightclickselect/MZ93/?sorting=hot
https://blenderartists.org/t/context-sensitive-menu-in-blender/515689/5