Detect subject hierarchy node deletion before its children get deleted

In a custom module I would like to detect the deletion of an item to take appropriate action before its children gets deleted. I observed that the signal SubjectHierarchyItemAboutToBeRemovedEvent of the item is emitted after the deletion of the childrens. Is there a way to detect that the item will be deleted before its childrens ?

To reproduce:

  • Load SampleData - Slicer Wiki MR-head.nrrd
  • Create a segmentation
  • In Data module, drag and drop segmentation on MR-head volume (to have segementation as children of MR-head)
  • Observe event with the following python snippet:
shNode=slicer.app.mrmlScene().GetSubjectHierarchyNode()

@vtk.calldata_type(vtk.VTK_INT)
def onShItemAboutToBeRemoved(caller, event, removedItem):
  removedNode = shNode.GetItemDataNode(removedItem) if removedItem else None
  if removedNode is not None and removedNode.IsA('vtkMRMLNode'):
    print("About to remove node = ", removedNode.GetName())

shNode.AddObserver(shNode.SubjectHierarchyItemAboutToBeRemovedEvent, onShItemAboutToBeRemoved)

Delete MR-head

Result:
About to remove node = Segmentation
About to remove node = MR-head

Would it help if we changed the SH code so that the about to remove event is invoked first on the parents? I don’t see any harm in that; it makes sense to “announce” the deletion of an object before the ones that its own deletion causes.

What do you think @lassoan ?