Enable Buttons and Display Properties if Certain Objects Selected

Hello, I am making an addon to generate some objects, and I need certain buttons and properties in my panel to be enabled only when these objects are selected. How would I go about changing what’s displayed in the panel when I change selection? Thanks in advance for any help!

You would make a poll classmethod for the panels that only returns True if all of your qualifications are met. For example, here is how to do that to a panel and an operator so that the panel is only visible and the operator is only available when an empty named “Empty” is selected:



import bpy

class SpecialNeeds:
    @classmethod
    def poll(self,context):
        return ((context.active_object != None) and
                (context.active_object.type == "EMPTY") and
                (context.active_object.name == "Empty"))

class SPECIAL_OT_operator(bpy.types.Operator,SpecialNeeds):
    bl_idname = "special.operator"
    bl_label = "Special:Operator"
    def execute(self,context):
        print("self:",self)
        print("context:",context)
        return {"FINISHED"}

class SPECIAL_PT_panel(bpy.types.Panel,SpecialNeeds):
    bl_label = "Testing Panel"
    bl_space_type = "VIEW_3D"
    bl_region_type = "TOOLS"
    bl_category = "Testing"

    def draw(self,context):
        layout = self.layout
        layout.label(icon="COLOR_BLUE")
        layout.label(__name__)
        layout.operator("special.operator")


def register():
    #bpy.utils.register_module(__name__)
    bpy.utils.register_class(SPECIAL_OT_operator)
    bpy.utils.register_class(SPECIAL_PT_panel)



You could test this code by putting it in a script inside your $scripts/startup/ folder but it won’t work when run straight from within blender’s text editor. This may be due to the fact that you can’t put panels in THAT region unless they are registered more proper-like, as addon and such. I tested the same code both as run from startup and as run from blender’s editor. Just wanted to make note so that you didn’t go trying this by pasting it in and running it with alt+P scratching your head wondering why… yes my example ONLY seems to work when run from as a file.

Thanks, works perfectly!

Awesome. Glad to hear it.

If the poll-check is too expensive, run your checks inside the operator and return {‘CANCELLED’} if necessary.