# How to hide/show Collections levels with python?

how do we hide show a collection in blender 2.8

let say that this is the path to my collection

bpy.data.collections['SCATTER: [Plane.001] Particles']


• The operator for that is bpy.ops.outliner.item_openclose(). Besides a custom context it also requires the cursor to be placed at the element that is toggled. I don't think this is practically possible for an add-on to do both because shifting the cursor with bpy.context.window.cursor_warp() would be very irritating to the user, but more importantly the x,y position of the collection in the outliner is unknown. – Robert Gützkow Nov 7 '19 at 14:57
• pfouah this is such a bad api implementation. this should be accessible right from data :( – DB3D Nov 7 '19 at 14:58

The operator that toggles the collection visibility in the outliner is bpy.ops.outliner.item_openclose(). Unfortunately it depends on the cursor position to determine the collection that should be toggled. While we could position the cursor with bpy.context.window.cursor_warp() the x and y coordinates of the collection in the UI remain unknown. It's therefore not realistically possible to perform this operation in a script or add-on.

I could get it to work with manually determined coordinates to position the cursor on the arrow icon in front of the collection.

import bpy

context = bpy.context.copy()

for area in bpy.context.screen.areas:
if area.type == 'OUTLINER':
for region in area.regions:
if region.type == 'WINDOW':
context['area'] = area
context['region'] = region
break
break

# Places the cursor directly on the arrow icon for the first collection with
# my screen resolution and UI layout.
bpy.context.window.cursor_warp(2150,1250)
bpy.ops.outliner.item_openclose(context, 'INVOKE_DEFAULT')

• Thanks for the response, the problem is that this script wouldn't work if the user doesn't have an outliner open in his window. – DB3D Nov 7 '19 at 15:33
• It doesn't work in general, since you don't know the x,y coordinates since the UI layout and screen resolution are likely different. Perhaps there is a different way to approach this problem. Why do you want to toggle the collection in the outliner? – Robert Gützkow Nov 7 '19 at 15:37
• because i'm creating collections and some users are annoyed to close them manually each time, which i understand. – DB3D Nov 7 '19 at 15:40
• There are some options, however they aren't very selective and also require a custom context. bpy.ops.outliner.show_one_level() for expanding or collapsing one level or bpy.ops.outliner.expanded_toggle() to expand or collapse all elements. – Robert Gützkow Nov 7 '19 at 15:54