Is there a way to programmatically achieve the same thing as pressing the 0
key the numpad?
2 Answers
The operator for switching the 3D view which is associated with numpad keys is view3d.viewnumpad()
. You have to be in the right context (3d_view) to use it and select which view you want to set:
import bpy
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
override = bpy.context.copy()
override['area'] = area
bpy.ops.view3d.viewnumpad(override, type = 'CAMERA')
break
Another way, without the operator would be:
import bpy
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
area.spaces[0].region_3d.view_perspective = 'CAMERA'
break
Which is equivalent to:
import bpy
area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
area.spaces[0].region_3d.view_perspective = 'CAMERA'
Other options are [‘PERSP’, ‘ORTHO’, ‘CAMERA’]
-
$\begingroup$ that is working if the area type is
'VIEW_3D'
, but is there another way, to achieve this thing without temporarily switch the area? $\endgroup$ Commented May 9, 2015 at 12:29 -
$\begingroup$ the context should be VIEW_3D , but you can do it without switching, I will edit $\endgroup$– ChebhouCommented May 9, 2015 at 12:30
-
$\begingroup$ just to be sure: there is no other way, then using the
bpy.ops
, right? (btw switching back and forth is way shorter than the solution you have provided after the edit -- but I have no idea, what is the advantage of you way vs. the "switching" way) $\endgroup$ Commented May 9, 2015 at 12:51
the best way is to put it into a function (e.g in the main of the template: simple operator)
def main(context):
if context.region_data.view_perspective in {'PERSP','ORTHO'}:
context.region_data.view_perspective = 'CAMERA'
else:
context.region_data.view_perspective = 'PERSP'
return {'FINISHED'}
notice region_data
another example to not do a loop over areas...
def execute(self, context):
context.space_data.overlay.show_extra_indices^= True
to switch show_extra_indices (edit mode) show_extra_indices
bpy.ops
thing that's fine, but I already "own" thecamera
and if I could assign it to a "view-slot" or something that would be awesome.. $\endgroup$