What is the corresponding event for 'changing the number of 3D widget' in python script?

Hello. I’ve been using the SlicerCustomAppTemplate to customize the slicer based on our needs.

I want to apply the customization for ‘every’ 3D widget. I found the following code from the script repository.

viewNode = slicer.app.layoutManager().threeDWidget(0).mrmlViewNode()
viewNode.SetBoxVisible(False)                             #Hide the 3d cube

controller = slicer.app.layoutManager().threeDWidget(0).threeDController()
controller.setBlackBackground()                           #Set the background color to be black

The problem is that this only applies to a single 3D widget. That is, if I change the layout type to ‘Dual 3D’ or ‘tripled 3D’, my customization only applies to the widget index 0.

So I change the above code as follows.

  num_3d_widgets = slicer.app.layoutManager().threeDViewCount
  # print(f"The number of 3d widgets is: {num_3d_widgets}")

  for i in range(num_3d_widgets):
    viewNode = slicer.app.layoutManager().threeDWidget(i).mrmlViewNode()
    viewNode.SetBoxVisible(False)                         #Hide the 3d cube

    controller = slicer.app.layoutManager().threeDWidget(0).threeDController()
    controller.setBlackBackground()                       #Set the background black

But this still is not perfect, because that script is applied only once when the program starts.
So, if I change the layout from single 3D widget to dual 3D widget, the customization for the second 3D widget is not applied.

How can I write the python script so that whenver the number of 3D widgets change, the above customization automatically applies to all 3D widgets?

I’ve been trying to find the proper event (such as slicer.vtkMRMLScene.NewSceneEvent) for this and the proper usage of slicer.mrmlScene.AddObserver, but this is pretty difficult to me. How should I handle this?

Thank you in advance!

You can define any layout you want (any number of any kind of views arranged in any way you prefer). See detailed instructions and examples in the script repository.