There is no single selection list for collections. We can open the Outliner in two different Blender areas, and select a different set of collections in each of them. Since the list of selected collections is different for each Outliner area, it can only be obtained through the context of this area.
The context can be accessed with operators. Having accessed the context through the operator, we can check the list of selected ID-objects in this context through the “selected_ids” list.
Let’s make a simple operator that prints a list of ID-objects from the context and register it in the Blender Python API:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class OUTLINER_OT_op(bpy.types.Operator): bl_idname = 'outliner.op' bl_label = 'Selected Collections' def execute(self, context): selection = context.selected_ids selected_collections = [sel for sel in selection if sel.rna_type.name == 'Collection'] print(selected_collections) return {'FINISHED'} bpy.utils.register_class(OUTLINER_OT_op) |
In the “execute” function, we first get a list of all selected ID-objects (ID-objects include scene objects, meshes, armatures, and collections as well) from the “selected_ids” property.
After that, we filter only “Collection” type objects and print the resulting list.
By executing our operator in the Outliner area, for example, by adding an operator call button to the Outliner interface or by binding the operator call to a hotkey, we successfully get a list of selected collections.
If we need to execute the operator from another area (for example, Text Editor or 3D Viewport), we need to override the context and call our operator with the overrided context.
1 2 3 4 5 6 7 8 9 10 |
override_context = bpy.context.copy() area = [area for area in bpy.context.screen.areas if area.type == "OUTLINER"][0] override_context['window'] = bpy.context.window override_context['screen'] = bpy.context.screen override_context['area'] = area override_context['region'] = area.regions[-1] override_context['scene'] = bpy.context.scene override_context['space_data'] = area.spaces.active bpy.ops.outliner.op(override_context) |
Finally we will get a list of selected collections:
1 2 |
# [bpy.data.collections['Collection 8'], bpy.data.collections['Collection 12'], bpy.data.collections['Collection 15 1']] |
Using these script from the script workspace and adding the override directly under the operator. It returns an error for line 9 about “selected_ds”
HI!
Try to use temp_override in last Blender versions.
https://b3d.interplanety.org/en/context-overriding-in-blender-3-2-and-later/