3
$\begingroup$

I'm trying to to add a node from a custom made panel which pops from a pie menu. And I want the node to appear at my mouse's location (see bpy.context.active_node.location below).

The problem is that 'mouse_region_x' and 'mouse_region_y' give me the x and y mouse coordinates according to the area's size. And as its size may vary, this would give me, each time, a different offset from the cursor when the node is placed. I want my mouse's coordinates of the Node Editor area to be translated to the Node Editor's "internal" blackboard coordinates.

    e = get_event()

    if context.material != None:
        bpy.ops.node.add_node(
            type="ShaderNodeGroup",
            use_transform=True,
            settings=[{"name":"node_tree", "value": "bpy.data.node_groups[\"%s\"]" % node_group_datablock_name}]
            )
        bpy.context.active_node.location = Vector((e.mouse_region_x, e.mouse_region_y)) # Need the coordinates here.

Any idea how to achieve this? Thanks.

enter image description here

$\endgroup$
2
  • $\begingroup$ did you solve this? $\endgroup$ – user3597862 May 5 at 14:54
  • $\begingroup$ Only partially. This code gives you the coordinates of the mouse inside the Node Editor's space: bpy.context.active_node.location = context.space_data.cursor_location My problem is since I'm opening a pie menu, then another panel from one of the pie's buttons so I can append a node tree, and the problem with the code above is that it takes into account the coordinates of where I clicked first just before I opened the pie menu, instead of where my mouse is now in the "pie button > panel space". $\endgroup$ – Ryxx May 7 at 18:20
2
$\begingroup$

this'll solve it for you:

def invoke(self, context, event):
    region = context.region.view2d  
    ui_scale = context.preferences.system.ui_scale     
    x, y = region.region_to_view(event.mouse_region_x, event.mouse_region_y)
    self.x,self.y = x /ui_scale,y/ui_scale
    return self.execute(context)

Then when you want to use it:

def execute(self,context):
    new_node.location.x = self.x
    new_node.location.y = self.y

    return {'FINISHED'}
$\endgroup$
2
$\begingroup$

Huge thanks for this. It's working perfectly now!
Here's the code that worked in my case:

e = get_event()

[...]

ui_scale = context.preferences.system.ui_scale
x, y = context.region.view2d.region_to_view(e.mouse_region_x, e.mouse_region_y)
x, y = x / ui_scale, y / ui_scale
bpy.context.active_node.location = Vector((x, y))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.