# How to add node in the center of the Shader Editor with python?

I would like to create a node, and center it in the node_tree view that is the "Shader Editor". Keeping in mind that this operator is only executed by a button in the context of the Shader Editor, so the context is correct.

I was wondering if it was possible to obtain the coordinates of the view, and find the center of it, to assign the coordinates to the new node created, so that it is placed exactly in the center of the view.

Below is an example of an operator creating a simple node, waiting to be positioned in the center of the Shader Editor view. (If possible)

I'd like to understand how you can get the position of the view, or something useful to position it correctly.

Simple test Creation of a node by operator:

class ADDNODE_OT_Test(bpy.types.operator):
bl_idname = "node.test"
bl_label = "Test"

def execute(self,context):
mat = bpy.data.materials["My_Material"]
nodes = mat.node_tree.nodes
#bsdf.location = (?,?) <--- Is possible to get and set the center of the view location into the Shader editor?
return{'FINISHED'}


Feed it into the transform operator.

Rather than place the node into the editor at the location of view centre, suggest: make active and feed the created (and / or other selected) nodes into the transform operator.

If you add say 3 nodes in your operator could make them relative to each other and let the user place them.

class AddMathNode(Operator):
items = [
(p.identifier, p.name, p.description)
]
#print(items)
operation : EnumProperty(
items=items,
name="Operation",
)

def execute(self, context):
# the material in the node editor
mat = context.material
# add a new math node to its nodes
# set some properties
n.operation = self.operation
n.name = self.operation.lower().title()
# make active
mat.node_tree.nodes.active = n

return bpy.ops.transform.translate('INVOKE_DEFAULT') # use translate


Putting in 2d region centre.

Most spaces in blender have a 2d region which is the window we look into. The tool panels, headers and other parts making up the area. Others like the 3d view have a 3d region.

If need be will supplement answer with how to place node right in the middle, but alas think that having the option to move and drop where I want feels more consistent with default behaviour.

• Hey, batFINGER very interesting using transform.translate But the problem remains similar, assuming that we move away from the center of the graph x = 0 and y = 0. This node is grabbed at a different point than it should be. That is, it doesn't stay in the center of the cursor, as I think it should do in this case. Try to move the visual away from the center of the X-Y graph and call the operator, you will see that the node is not out of sight. (I hope I'm not wrong) Nov 1 '20 at 17:38