4

Let's say I have a pointer property:

collection: bpy.props.PointerProperty(type=bpy.types.Collection, name="Collection")

Then I output this property using UILayout.prop():

row.prop(my_object, "collection")

So that I can select a collection to assign it to this pointer property:

enter image description here

Is there a way to filter out some collections, for example, remove a collection that contains the active object?

Crantisz
  • 35,244
  • 2
  • 37
  • 89

1 Answers1

4

You can leverage a property's poll callback attribute very similarly to this Q&A (might almost say this is a duplicate)

This is called for each possible object in order to decide whether or not it's suited to populate the property.

You don't have direct access to the current context so it might be meh if you heavily rely on it but you can still use bpy.context.

import bpy

class HelloWorldPanel(bpy.types.Panel): bl_label = "Hello World Panel" bl_idname = "SCENE_PT_hello" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "scene"

def draw(self, context):
    self.layout.prop(context.scene, "my_collection")


def is_collection_ok(scene, col): return bpy.context.active_object.name not in col.all_objects

def register(): bpy.utils.register_class(HelloWorldPanel) bpy.types.Scene.my_collection = bpy.props.PointerProperty(type=bpy.types.Collection, name="My Collection", poll=is_collection_ok)

def unregister(): bpy.utils.unregister_class(HelloWorldPanel) del bpy.types.Scene.my_collection

if name == "main": register()

Result :

enter image description here

Gorgious
  • 30,723
  • 2
  • 44
  • 101