I was wondering if anyone had any insights into this problem (as it’s driving me insane …)
I’ve done my best to describe it. Sorry if it’s a bit long, and let me know if you need clarification.
Background / Overall Goal
I have a script that runs from the render context of the properties panel. This script cycles through the materials of objects selected in the 3D View, and “fiddles” with the nodes.
Simply put - I want to ungroup all node groups each material.
As best I can tell, there doesn’t seem to be a way to ungroup node groups via bpy.data. The only solution would seem to be copying each node from the node group node_tree to the material node_tree one by one and recreating the links. This seems like a nightmare.
So, instead I turn to bpy.ops.node.group_ungroup() - but I cannot get this to run consistently. See the next heading.
Issues with bpy.ops.node.group_ungroup()
Consider this proof of concept code. Assume the node group in question is already selected and active:
#Store where we started
home_area = bpy.context.area.type
home_ui = bpy.context.area.ui_type
#Change context so that bpy.ops.node.group_ungroup() will work
bpy.context.area.type = “NODE_EDITOR”
bpy.context.area.ui_type = “ShaderNodeTree”
bpy.context.space_data.shader_type = “OBJECT”
#Restore where we started from
bpy.context.area.type = home_area
bpy.context.area.ui_type = home_ui
If I open Blender and input that code into the text editor and hit run, it works! The selected node group is ungrouped.
If I put that code into my existing script (the one mentioned above, that runs from the render context of the properties panel) it fails
The properties panel is changed into the NODE_EDITOR, but then the script crashes with “context is incorrect” for bpy.ops.node.group_ungroup()
It leaves my properties panel in the node_editor view.
And even weirder
After it crashes, if I simply change my the (now) node_editor panel back to the properties panel, and click the exact same button again, IT WORKS JUST FINE.
Clearly I am missing something about the required context for bpy.ops.node.group_ungroup().
How can it crash for context incorrect, and then run the second time I click the same button? Having changed nothing else.
Could it be something to do with my mouse position? The last part of the window that I clicked on?
What’s the secret?