We can enable and disable a collection from interaction with the scene by switching the checkbox located in the Outliner opposite the name of the desired collection. In order to do this using the Blender Python API, we need to access the collection through the View Layer of the scene on which the desired collection is located.
The “exclude” property is responsible for turning a collection on and off. However, the scene collection (bpy.context.collection) does not have this property.
This property can be accessed through the View Layer collection.
The currently active collection on the currently active View Layer:
1 2 3 |
bpy.context.view_layer.active_layer_collection # bpy.data.scenes['Scene']...LayerCollection |
Disabling the collection (off the checkbox):
1 |
bpy.context.view_layer.active_layer_collection.exclude = True |
And enabling the collection back (on the checkbox):
1 |
bpy.context.view_layer.active_layer_collection.exclude = False |