# Automatically Centering 3D View in 3D Slicer

**URL:** <https://discourse.slicer.org/t/automatically-centering-3d-view-in-3d-slicer/39950>\
**Category:** Support\
**Created:** [October 31, 2024, 8:57am UTC](https://discourse.slicer.org/t/automatically-centering-3d-view-in-3d-slicer/39950 "2024-10-31T08:57:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![huwqchn](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/huwqchn/32/77074_2.png) [@huwqchn](https://discourse.slicer.org/u/huwqchn)\
**Post date:** [October 31, 2024, 8:57am UTC](https://discourse.slicer.org/t/automatically-centering-3d-view-in-3d-slicer/39950/1 "2024-10-31T08:57:08Z")

</div>

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:

```auto
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:

```auto
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!

---

<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:** [October 31, 2024, 9:55am UTC](https://discourse.slicer.org/t/automatically-centering-3d-view-in-3d-slicer/39950/2 "2024-10-31T09:55:26Z")

</div>

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

Note that then the callback should look like this:

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

```

(no `self` if not in a class of course)
