1
$\begingroup$

How can I add a remove button similar to the Parent property in Object?

Actually, I need to create something exactly similar to the Parent property where I can optionally select an object from objects according to a criteria.

My problem is how to make it optional or how to add a remove button. Unlike an EnumProperty.

enter image description here

$\endgroup$
2
$\begingroup$

One way is via a UILayout.prop_search

In example below the string property scene.target_object is set to the name of one of the objects in the scene. Also note the "X" remove button once set.

import bpy
from bpy.props import StringProperty

class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "scene"

    def draw(self, context):
        layout = self.layout

        scene = context.scene

        row = layout.row()
        row.prop_search(scene, "target_object", scene, "objects")
        print(scene.target_object)

def register():
    bpy.types.Scene.target_object = StringProperty()
    bpy.utils.register_class(HelloWorldPanel)

def unregister():
    bpy.utils.unregister_class(HelloWorldPanel)

if __name__ == "__main__":
    register()

On the selecting objects by a criteria, you can also use a user defined collection property as the search data. For instance in my sound_drivers addon scene.driver_objects is defined as a PointerProperty, scene.driver_objects.armatures is a CollectionProperty. The collection is populated by all the armatures (by name) with drivers in the scene.

    row.prop_search(scene, "target_object",
                    scene.driver_objects, "armatures")
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.