# Detect subject hierarchy node deletion before its children get deleted

**URL:** <https://discourse.slicer.org/t/detect-subject-hierarchy-node-deletion-before-its-children-get-deleted/27517>\
**Category:** Development\
**Tags:** subject-hierarchy\
**Created:** [January 28, 2023, 3:38pm UTC](https://discourse.slicer.org/t/detect-subject-hierarchy-node-deletion-before-its-children-get-deleted/27517 "2023-01-28T15:38:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Albi](https://avatars.discourse-cdn.com/v4/letter/a/a88e4f/32.png) [@Albi](https://discourse.slicer.org/u/Albi)\
**Post date:** [January 28, 2023, 3:38pm UTC](https://discourse.slicer.org/t/detect-subject-hierarchy-node-deletion-before-its-children-get-deleted/27517/1 "2023-01-28T15:38:07Z")

</div>

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](https://www.slicer.org/wiki/SampleData) 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:

```python
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

---

<div class="post-metadata">

**Author:** ![cpinter](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/cpinter/32/7995_2.png) [@cpinter](https://discourse.slicer.org/u/cpinter)\
**Post date:** [February 9, 2023, 9:59am UTC](https://discourse.slicer.org/t/detect-subject-hierarchy-node-deletion-before-its-children-get-deleted/27517/2 "2023-02-09T09:59:45Z")

</div>

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 ?
