2
$\begingroup$

Trying to work with nodes in a ShaderNodeTree on a material I've just created, and I'm getting the dreaded "context is incorrect" error.

Here's some code I successfully ran in the Blender UI:

def test():
    C.window.workspace = D.workspaces['Shading']
    new_material = D.materials.new('color_ramp')
    new_material.use_nodes = True
    C.active_object.data.materials.append(new_material)
    C.window.screen.areas[3].type = 'NODE_EDITOR'
    C.window.screen.areas[3].ui_type = 'ShaderNodeTree'
    spaces = C.window.screen.areas[3].spaces
    return spaces[0]

With an object selected, this correctly switches the window, creates a new material, assigns it to the object, switches the area to the Node Editor, and even has the main node selected in the Node Editor area. Calling data = test() and then calling data returns:

bpy.data.screens['Scripting']...SpaceNodeEditor

and does not allow me to deselect the main node, nor does it allow me to add new nodes. From the code of the poll() function for nodes/node trees, I was able to see the context needs to be in the Node Editor and have a node tree selected. Calling data.node_tree in the UI correctly prints the node_tree, but interestingly enough my program I'm building does not.

Does anyone know the correct context for working with nodes/node trees?

EDIT: I added some print statements to the function to see if I could see what was going wrong with the context. Looks like it isn't changing the Workspace properly, which could I suppose be part of the issue? Even though it's in the Node Editor area...I'm not quite sure.

$\endgroup$
9
  • $\begingroup$ I recently posted regarding context.temp_override here but you will need to adjust for the shading area $\endgroup$
    – Ratt
    Aug 29, 2023 at 22:38
  • $\begingroup$ you can read more about context override in blender.stackexchange.com/questions/6101/… and use NODE_EDITOR as the area type when overriding. for example you can easily deselect the nodes using this code $\endgroup$ Aug 30, 2023 at 1:38
  • $\begingroup$ @HarryMcKenzie I'm getting a StopIteration error when I run that code, unfortunately. I know I need to do a temp_override, I just can't get the context correct. It seems to be ignoring me trying to set the proper context. $\endgroup$ Aug 30, 2023 at 10:20
  • $\begingroup$ imgur.com/a/X4l3UA9 $\endgroup$ Aug 30, 2023 at 10:28
  • $\begingroup$ @DevinGardner because one of the areas need to be the shader node open. $\endgroup$ Aug 30, 2023 at 11:17

1 Answer 1

2
$\begingroup$

Similar issue with this thread that has the same unintuitive solution:

area.spaces.active.node_tree = nodes #add this line before the ops statement
bpy.ops.node.select(deselect_all=True)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .