Applying a viewport camera change in python?

Hi,
I struggled a bit for the title, so let me elaborate a bit: I’m writing a short bit of code and at one point I select an object and align the view to it, using the following command:

for area in bpy.context.screen.areas:
            if area.type == 'VIEW_3D':
                ctx = {
                    "window": bpy.context.window, # current window, could also copy context
                    "area": area, # our 3D View (the first found only actually)
                    "region": None # just to suppress PyContext warning, doesn't seem to have any effect
                }
                bpy.ops.view3d.view_axis(ctx, type='TOP', align_active=True)

Which seems to work fine since when the script is finished I indeed see that the view changed on the viewport. However, few lines after in my script, I use the project from view uv operator and there it doesn’t use the updated view (the one aligned to the object, that is), but rather the intial view, i.e the view that was used when clicking “Run Script”. The chunk of code is the following:

        for area in bpy.context.screen.areas:
                if area.type == 'VIEW_3D':
                    for region in area.regions:
                        if region.type == 'WINDOW':
                            ctx = {'area': area, 'region': region, 'edit_object': bpy.context.edit_object}
                            bpy.ops.mesh.select_all(action='SELECT')
                            bpy.ops.uv.project_from_view(ctx , orthographic=True, camera_bounds=False, correct_aspect=False, scale_to_bounds=True)

Any idea how to make sure the project from view uses the proper view ? What did I do wrong ?

Thanks!

/T

Try calling update():

for area in bpy.context.screen.areas:
            if area.type == 'VIEW_3D':
                ctx = {
                    "window": bpy.context.window, # current window, could also copy context
                    "area": area, # our 3D View (the first found only actually)
                    "region": None # just to suppress PyContext warning, doesn't seem to have any effect
                }
                bpy.ops.view3d.view_axis(ctx, type='TOP', align_active=True)
                area.spaces.active.region_3d.update()  # <---
1 Like

Yep, worked like a charm! Thank you so much, wasn’t aware of that trick!

1 Like