Skip to content

Instantly share code, notes, and snippets.

@dustractor
Created November 2, 2021 00:22
Show Gist options
  • Save dustractor/66cc0f990c2edaebc6b1f1d1f65838a2 to your computer and use it in GitHub Desktop.
Save dustractor/66cc0f990c2edaebc6b1f1d1f65838a2 to your computer and use it in GitHub Desktop.
Blender CollectionProperty / template_list example
import bpy
bl_info = {
"name": "CollectionProperty Test",
"blender": (2,80,0),
"category": "Test"
}
def _(a=None,b=[]):
if a:
b.append(a)
return a
else:
return b
@_
class COLPROPTEST_OT_move(bpy.types.Operator):
bl_idname = "colproptest.move"
bl_label = "move"
index_from: bpy.props.IntProperty(default=-1)
index_to: bpy.props.IntProperty(default=-1)
def execute(self,context):
context.active_object.testitems.move(self.index_from,self.index_to)
return {"FINISHED"}
@_
class COLPROPTEST_OT_add(bpy.types.Operator):
bl_idname = "colproptest.add"
bl_label = "add"
def execute(self,context):
ob = context.active_object
obs = [_.name for _ in context.selected_objects if _ != ob]
for eachob in obs:
newitem = ob.testitems.add()
newitem.name = eachob
return {"FINISHED"}
@_
class COLPROPTEST_OT_remove(bpy.types.Operator):
bl_idname = "colproptest.remove"
bl_label = "remove"
index: bpy.props.IntProperty(default=-1)
def execute(self,context):
context.active_object.testitems.remove(self.index)
return {"FINISHED"}
@_
class COLPROPTEST_PT_panel(bpy.types.Panel):
bl_idname = "COLPROPTEST_PT_panel"
bl_label = "colproptest panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "test"
@classmethod
def poll(self,context):
return context.active_object
def draw(self,context):
layout = self.layout
split = layout.split(factor=0.92)
col1,col2 = split.column(),split.column(align=True)
ob = context.active_object
col1.template_list("UI_UL_list","custom_id_blah",
ob,"testitems",
ob,"testitems_i")
col2.operator("colproptest.add",text="",icon="ADD")
col2.operator("colproptest.remove",text="",icon="REMOVE").index = ob.testitems_i
col2.separator()
op = col2.operator("colproptest.move",text="",icon="TRIA_UP")
op.index_from = ob.testitems_i
op.index_to = ob.testitems_i - 1
op = col2.operator("colproptest.move",text="",icon="TRIA_DOWN")
op.index_from = ob.testitems_i
op.index_to = ob.testitems_i + 1
if ob.testitems_i > -1:
active_item = ob.testitems[ob.testitems_i]
box = layout.box()
box.label(text=active_item.name)
box.prop(active_item,"number")
@_
class TestItem(bpy.types.PropertyGroup):
name: bpy.props.StringProperty()
label: bpy.props.StringProperty()
number: bpy.props.IntProperty(default=42)
def register():
list(map(bpy.utils.register_class,_()))
bpy.types.Object.testitems = bpy.props.CollectionProperty(type=TestItem)
bpy.types.Object.testitems_i = bpy.props.IntProperty(min=-1,default=-1)
def unregister():
del bpy.types.Object.testitems_i
del bpy.types.Object.testitems
list(map(bpy.utils.unregister_class,_()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment