Selecting from property lists in Blender addons

In a previous article I reported on the difficulties that crop up when you want to present a dynamic list of choices, like a dropdown to select an object in a scene. Now it appears that for many situations there is a better way that was somewhat hidden in Blender's API docs: prop_search().
What this poorly documented function does is putting a widget in the layout of your addon that lets the user select an item from a property list that is part of an object the name of which subsequently assigned to a property on another object.
That may sound a bit cryptic at first but say you want to let the user choose a vertex group on the active object and store the name of this chosen vertex group in a string property. Then all you have to do is to define that property in your operator and call prop_search() in the draw() function:
vertexgroup = StringProperty(name="Vertex group")
 
def draw(self, context):
    layout = self.layout
    # get the mesh data of the active object
    ob = context.active_object.data
    # display a vertex choice widget that assign to our string property
    layout.prop_search(self, "vertexgroup", ob, "vertex_groups", text="Vertex Group")
It automatically assigns a proper icon as well:

This works for basically anything that is a bpy.types.bpy_prop_collection, like objects in a scene or vertex groups in mesh data. There's also a prop_enum() that lets you select an item from a enumerated property.

No comments:

Post a comment