Change the visibility of collections locally to viewport with python


We have a proyect with 2 viewports in the same interface. We need an operator that can click on one of the viewports and change the visibility of some collections locally in the viewport that has been clicked.

We have find the following code for set the view of the viewport in local mode:

bpy.context.space_data.use_local_collections = True

And the only method we have found to change the visibility of a collection:

bpy.ops.object.hide_collection(context, collection_index=i, toggle=True)

That inverts the visibility of the current collection.

The problem is, that this method changes visibility globally and we want to change it locally.

We know that the execution context is important, but since we are executing it from an operator in the tools window of the viewport, we believe that we are doing that correctly.

Other variables as disabled in viewport, have a direct access to the variable via python, example:[“Collection”].hide_viewport = False

But the variable that we need in local does not have it.

Manually, in the interface, it is simple to do, as seen in the image

The final question is, is there any way to edit via python, the visibility of the collections locally to the viewport?

(moved this to the Python API section since this is not related to Blender development).

You need to pass the viewport that has the local collections enabled as an overriden context argument.

1 Like

Oh thanks!

We have reviewed it and although we already did the overwriting of our context, there was our problem.

 ctx_override = context.copy()
 ctx_override['area'] = get_area(context, 'VIEW_3D')

The function get_area (…) returned the area of ​​the viewport in which to make the changes, but did not select the correct viewport, since having two in the interface always takes the first one located in the vector, which was a viewport with local visibility of collections deactivated.

Now we differentiate the viewports by their width to make the changes in the correct viewport