How can I get the collection that is selected in the outliner in python?

Hello all,

I am writing an exporter and would like the user to select a collection in the outliner and I will export all the objects belonging to that collection.

unfortunately, I can’t find a way to get the name of the currently highlighted collection from the outliner. Is there a way to do this?

Thanks,
Koen

Have you tried bpy.context.collection?

1 Like

duh, sorry about that, maybe to obvious, or maybe time for a vacation :slight_smile: Thanks JYoshi!

Koen

1 Like

But this does not work when you have more than 1 collections selected…
Is there a way to work with several selected collections

in TextEditor type following code

import bpy

# Set the area to the outliner
area = bpy.context.area
old_type = area.type 
area.type = 'OUTLINER'

# some operations
ids = bpy.context.selected_ids
names = [o.name for o in ids]
print (names)

# Reset the area 
area.type = old_type  

it return names of selected elements in outliner.
if you select only collections it will return selected collection names.

But you need in text editor window switch to outliner, select there elements, then switch back to text editor and then run code.

context.selected_ids it’s a new command and not very nice organized

In the Outliner, operators can get a list of the selected data-blocks, via bpy.context.selected_ids (rBaf008f55). This may become available in more editors in future (from here).

I don’t think it is needed to switch to the outliner, I use this:

import bpy

a=bpy.context.view_layer.active_layer_collection.collection

col = bpy.data.collections.get(a.name)

print(col)

He needs to get multiple selected collections.
In your case, you will get only one active collection.

1 Like

Sorry didn’t read the question properly :slight_smile: