6
$\begingroup$

I can get an item in my CollectionProperty using index. Like this:

item = context.scene.my_collection_prop[index]

But how to change the item's index? I want to put the item into index=0.

$\endgroup$

1 Answer 1

10
$\begingroup$

Use my_collection_prop.move(item_index, target_index), it let's you place a collection item (specified via its index in the current collection) to an arbitrary position in the collection.

In a collection with 3 items, you would call move(2, 0), to put the last item on top of the list. The other two items remain in order, there's no swapping of the source and target item:

import bpy

bpy.types.Scene.coll = bpy.props.CollectionProperty(type=bpy.types.PropertyGroup)
coll = bpy.context.scene.coll
coll.clear() # in case you re-run this script, empty the collection

# item 0
item = coll.add()
item.name = "First"

# item 1
item = coll.add()
item.name = "Second"

# item 2
item = coll.add()
item.name = "Third"

print("Before:")
for i, item in enumerate(coll, 1):
    print("{}. {}".format(i, item.name))

coll.move(2, 0)

print()
print("After:")
for i, item in enumerate(coll, 1):
    print("{}. {}".format(i, item.name))

"""
Before:
1. First
2. Second
3. Third

After:
1. Third
2. First
3. Second
"""
$\endgroup$
2
  • 1
    $\begingroup$ Thanks. Strange that add() and move() methods are not documented in blender python api. $\endgroup$
    – mifth
    Commented Jan 22, 2015 at 20:58
  • 2
    $\begingroup$ The methods belong to the class bpy_prop_collection_idprop, which is somewhat an internal type and does indeed not appear anywhere in the documentation. If you register a collection property however, you may call dir(…) on an instance (if registered on bpy.types.Scene, for example bpy.context.scene) to see all properties and methods: ['__doc__', 'add', 'clear', 'move', 'remove']. $\endgroup$
    – CodeManX
    Commented Jan 23, 2015 at 1:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .