Binding a custom user operator to a tool

We can bind not only common system operators to buttons on the toolbar (T-Panel), but also custom ones created by us. The principle of connection in Blender Python API is the same for both system and custom operators.

For example, let’s define a custom operator that adds a UV Sphere to the scene at a random location between 0 and 10.

Inside the execute() function, we call the operator for adding a sphere to the scene, specifying random coordinates from 0 to 10 in the “location” parameter, but here you can type any code you need.

Register our custom operator in the Blender API.

Next, define a class for the tool and its button in the T-panel.

The most important thing for us here is the “bl_keymap” tuple, in which we specify the binding of operators to this tool, and assign the conditions for their execution.

Our “bl_keymap” has only one element, also a tuple consisting of three elements. The first element – here we specify the “bl_idname” of our operator, we defined earlier. The second element specifies the action by which the operator will be executed – a left mouse click. The third element is used to pass parameters to the operator, we don’t need it now, so we set it to None.

Register our tool class in the Blender Python API.

And force a redraw of all areas so that our new tool button is immediately drawn.

Now, when our TestTool tool is active (selected) in the toolbar and the user left-clicks on the viewport, our custom “test.test” operator will be called with each click, which will result in a UV Sphere being added to the scene area with coordinates from 0 to 10.

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments