Delayed callback when SegmentationNode is added to the scene

I’ve created a listener when SegmentationNodes are added to my scene, something like this:

def onNodeAdded(caller, event, node):
    if node.IsA( "vtkMRMLSegmentationNode" ):
        # call `myFunction()` in current thread
        myFunction( node )

slicer.mrmlScene.AddObserver(slicer.vtkMRMLScene.NodeAddedEvent, onNodeAdded)

Actually, I’m performing some editor effects automatically whenever I add a SegmentationNode.

If I don’t use the callback (i.e. slicer.mrmlScene.AddObserver() not called) and do the steps manually: call myFunction() in the interpreter after the node was added, things works as expected. However, if I add the callback as an observer (above code block), something wrong happens so myFunction() fails. I guess this is because the SegmentationNode has to be fully added in order for myFunction() to work.

How can I call myFunction() after the SegmentationNode and its dependencies was completely added? A timed callback to myFunction() can be a solution (practically but not completely safe in theory).

Yes, probably you want to wait for the segmentation node to get a default display node, etc. You can add a delayed callback (which is called when the application becomes idle) like this:

qt.QTimer.singleShot(0, myCallback)
1 Like