Automatically Centering 3D View in 3D Slicer

Hi everyone,

I’m trying to make the 3D view automatically center whenever a new object is added. My current code mostly works but fails when I hide the 3D box and axis. Here’s what I have:

layoutManager = slicer.app.layoutManager()
threeDWidget = layoutManager.threeDWidget(0)
threeDView = threeDWidget.threeDView()
renderer = threeDView.renderWindow().GetRenderers().GetFirstRenderer()

initialActorCount = renderer.GetActors().GetNumberOfItems()
print("Initial actor count:", initialActorCount)

def checkForNewObject(caller, event):
    global initialActorCount
    currentActorCount = renderer.GetActors().GetNumberOfItems()
    
    if currentActorCount > initialActorCount:
        print("New object added to 3D view")
        print("Current actor count:", currentActorCount)

        slicer.app.processEvents() 
        threeDView.resetFocalPoint()
        
    initialActorCount = currentActorCount

renderer.AddObserver(vtk.vtkCommand.ModifiedEvent, checkForNewObject)

The issue arises when I hide the 3D box and axis using:

viewNode.SetBoxVisible(False)
viewNode.SetAxisLabelsVisible(False)

With these settings, the automatic centering doesn’t work as expected. Does anyone know why this happens or have suggestions for a solution?

Any help would be appreciated!

I’d probably connect the callback to the event slicer.vtkMRMLScene.NodeAddedEvent.

Note that then the callback should look like this:

@vtk.calldata_type(vtk.VTK_OBJECT)
def onNodeAdded(self, caller, event, calldata):

(no self if not in a class of course)