Adding new items to the context menu

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.

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:

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.

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.

We can add our function to this class using the append command:

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:

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
internetuser9000D
1 year ago

I know that it is possible to put new options in submenus that are built in, for instance: tex-tools adds options to the UV Unwrap sub-section of the right click menu, but there is no documentation as far as I can tell. I tried for an hour yesterday to stick a new operator in the “Separate” sub-section of the edit mesh context/right click menu and failed. Don’t suppose you have any idea how you would do that? Cheers!