Quite an old post, but I came across the same problem and that solution pretty much worked!
I had to switch the event type from `MDGMessage.addConnectionCallback` to `MEventMessage.addEventCallback` with the idle event, reason being that you need to know when to manually remove the callback, and with the connection callback it wasn't clear in my case.
E.g. I was trying to attach a callback to whenever a constraint is made and play with the related transforms, but in the addConnectionCallback I wouldn't have a good reasoning to tell Maya when all the related objects were done connecting to the newly made constraint. This is why the idle event worked better, since Maya just waits until all its previous operations were done before executing that new callback.
It's a bit messy, but here's a trickled down version of what I wrote which is basically a class that can get new node types and attach callbacks for when they're made, and do whatever needs to be done with these new nodes after they've been properly connected to the DG graph:
import pymel.core as pm
import maya.api.OpenMaya as om2
class NewNodeTypeCallbacksManager():
_callbacks_list = []
_idle_timed_callback = None
_new_node = None
def createNewNodeCallbacks(self, node_type):
new_node_type_callback = om2.MDGMessage.addNodeAddedCallback(self._newNodeMadeCallback, node_type)
self._callbacks_list.append(new_node_type_callback)
def removeNewNodeCallbacks(self):
if self._callbacks_list:
for callbacks in self._callbacks_list:
om2.MMessage.removeCallback(callbacks)
self._callbacks_list = []
def _newNodeMadeCallback(self, *args):
obj_handle = om2.MObjectHandle(args[0])
if obj_handle.isValid():
self._new_node = pm.ls(om2.MFnDependencyNode(obj_handle.object()).name())
self._idle_timed_callback = om2.MEventMessage.addEventCallback('idle', self._idleTimedCallback, clientData=None)
def _idleTimedCallback(self, *args):
om2.MEventMessage.removeCallback(self._idle_timed_callback)
self._idle_timed_callback = None
self.doSomethingAtIdleEvent(self._new_node[0])
@staticmethod
def doSomethingAtIdleEvent(new_node):
# Do whatever you need to do with the new node,
# after Maya has processed it into the DG graph
# and all the node's info is valid.
pass
Hope that helps if anyone ever run into this in the future! 😀