Set a dynamic enum drop down list to a specific item

Heya everyone!

First post! YAY :wave:

hate to start my first post with a question, but here goes. What I am trying to do:

  • I want to dynamically fill the drop down list with the available scene collections. This works!
  • When I select a different object in the scene, I want to highlight/select the collection the object is linked to in the drop down list.
  • When I select a collection from the drop down list I want the object to be linked to the selected collection.

I can’t figure out how to change the currently selected item… In c# you can just do this
var_enum = MyEnum.State; But this does not seem to work here… If someone can point me in the right direction, it would be much appreciated.

Thanks!

import bpy
import math
from mathutils import Vector
from bl_ui.properties_data_modifier import DATA_PT_modifiers
from bpy.props import EnumProperty
from bpy.types import PropertyGroup

def get_collections_list(self, context):
    count = 0
    items = []
    cols = bpy.data.collections
    for col in cols:
        identifier = col.name
        name = col.name
        description = "Add object(s) to collection " + col.name        
        number = count
        items.append((identifier, name, description, number))
        count += 1  
    
    return items

def get_enum_number(scene, context):
    count = 0    
    items = []
    cols = bpy.data.collections
    for col in cols:        
        if col.name == bpy.context.object.users_collection[0].name :
            number = count
            return count
        count += 1
        
    return 0

class MyProperties(bpy.types.PropertyGroup):
    my_enum : bpy.props.EnumProperty(
        name="Collections",
        default=None,
        description="Collection",               
        items= get_collections_list
    )
              
class ENUM_PT_enum_example (bpy.types.Panel):
    bl_label = "Type Selection" 
    bl_idname = "PT_TypeSelection" 
    bl_space_type = "VIEW_3D" 
    bl_region_type = "UI" 
    bl_category = "Enum_Example"    
    
    def draw(self, context):
        layout = self.layout
        scene = context.scene
        mytool = scene.my_tool
        objs = bpy.context.selected_objects        
        
        row = layout.row()
        mytool = scene.my_tool        
        row.prop(mytool , "my_enum")       
         
classes = [MyProperties, ENUM_PT_enum_example]     
        
def register():
    for cls in classes : 
        bpy.utils.register_class(cls)
    
        bpy.types.Scene.my_tool = bpy.props.PointerProperty(type=MyProperties)
    
def unregister():    
    for cls in classes : 
        bpy.utils.register_class(cls)
    
        del bpy.types.Scene.my_tool
     
if __name__ == "__main__":
    register()
bpy.context.scene.my_tool.my_enum

This will return the identifier of current item of enum.
And to change the enum you just do

bpy.context.scene.my_tool.my_enum = 'Identifier of item which you want to set'