Question regarding expanding/collapsing collection in outliner in 2.8

Hi,
So I’m currently working on an addon to make images of models quick and easy.
I have added my cameras and other objects to collections in the outliner in
order to make things less cluttered. But I can’t manage to find any way
to collapse the collections. If that were possible it would really make things
tidier.

The closest thing I can find in the API documentation for 2.8
https://docs.blender.org/api/current/bpy.ops.outliner.html
is bpy.ops.outliner.show_one_level(open=True)
But that does not seem to do the trick. (Tried setting the open=False)
Is there anybody who has found a way to do this?


There aren’t any good ways of expanding/collapsing in the api yet, though this has been requested before. It’s possible to use the outliner operators in a specific sequence to get the desired effect.

Maybe this will work for you.

import bpy

def toggle_expand(context, state):
    area = next(a for a in context.screen.areas if a.type == 'OUTLINER')
    bpy.ops.outliner.show_hierarchy({'area': area}, 'INVOKE_DEFAULT')
    for i in range(state):
        bpy.ops.outliner.expanded_toggle({'area': area})
    area.tag_redraw()


if __name__ == '__main__':
    context = bpy.context
    toggle_expand(context, 2)

1 will expand all collections,
2 will collapse them.

Thanks for the quick answer @iceythe !
When I tried using your code It collapses everything but the recently created collection.
I wanted the recently created collection to be collapsed as well.
Anyways, this is good enough, it makes it way less cluttered.
I was really pulling my hair on this one, thanks for your help!

bpy.ops.wm.redraw_timer(type=‘DRAW_WIN’, iterations=1)

before the ‘collapse call’ to refresh! took me awhile to find this for the newly created collections

Nice! I was pretty much giving up hope on that one.
I will have look and see if it works when I get some
time for this project.