How to call bpy.ops.view3d.view_center_cursor() from console

I am trying to get this to work but am constantly getting an error ‘expected a view3d region’.
I can’t wrap my head around this.

This is a context problem. For an operator to function correctly, it expects to be called within the correct context.

When typing in the script editor, you are currently in the following context:

Screen "Scripting"
Area "Console"
Region "Window" for the console

But that operator needs to be invoked within a 3d view Area.

So you have to override the context to be the correct one:

# For every screen in the file...
for screen in bpy.data.screens:

    # Find all the 3d viewports...
    for area in (a for a in screen.areas if a.type == 'VIEW_3D'):

         # Now find the Window region too for that area...
        for region in (r for r in area.regions if r.type == 'WINDOW'):

            # Ok, we found the data we need to override
            # at minimum the 'area' and 'region' needs to be set, but here I set all 3 as an example
            override = {'screen': screen, 'area': area, 'region': region}
            bpy.ops.view3d.view_center_cursor(override)

Note: The above will change the view for every 3d viewport in your file. I leave it to you to ultimately determine which 3d view is affected and to stop the loops as needed.

1 Like

Thanks.

When I was trying to figure it out I iterated over the areas and the regions but couldn’t find a region named ‘view3d’.
Could you explain why the ‘WINDOW’ region is used here?

If anything I think the initial error is worded incorrectly. The “expected a view3d region” probably should have said “expected a view3d area” probably?

Regions will typically be one of the following:
TOOL_HEADER
HEADER
TOOLS
UI
WINDOW

I’m actually unsure of the difference between some of those. It’s also a guessing game to know which of those are expected by an operator unless you look at the actual source code sometimes. Perhaps the initial error should list both or all constraints when they’re known but I’m not sure if it’s feasible to make the change as I’m unfamiliar with that portion of blender.

2 Likes