The DoF (depth of field) parameter in the final render is responsible for blurring details in the background or objects close to the camera. During the modeling process, enabling DoF is distracting, so it’s usually only enabled for rendering. However, for proper scene setup, enabling DoF directly in the viewport can be useful.
We can manually enable DoF in the 3D viewport through the viewport shading menu. Expand the menu and on the “Depth of Field” checkbox.
To disable DoF in the viewport, off the checkbox.
DoF in the viewport can also be enabled and disabled using the Blender Python API.
First, ensure DoF is enabled for the camera. Get a pointer to the currently active camera in the scene:
|
1 2 3 |
active_camera = bpy.context.scene.camera # bpy.data.objects['Camera'] |
And enable depth of field for it:
|
1 |
active_camera.data.dof.use_dof = True |
We can also set DoF parameters for the camera using its pointer. For example, focal length and aperture:
|
1 2 |
active_camera.data.dof.focus_distance = 8 active_camera.data.dof.aperture_fstop = 0.3 |
Now let’s enable DoF in the viewport.
To do this, we need to set the viewport shading property “use_dof” to True.
To ensure that the code executes correctly from another context, for example, if we’re executing a script from the Text Editor, we need to temporarily override the context to the viewport context.
Get a pointer to the viewport’s area:
|
1 2 3 4 |
area = next((_area for _area in bpy.context.screen.areas \ if _area.type == 'VIEW_3D'), None) # <bpy_struct, Area at 0x000001E5A7DAB840> |
And with context overridde, set the value of the viewport property we need.
|
1 2 |
with bpy.context.temp_override(area=area): bpy.context.space_data.shading.use_dof = True |
To disable DoF in the viewport, we need to override the context in the same way and set “use_dof” property to False.

.blend file on Patreon