0
$\begingroup$

How would you print to the info if no object is selected (no active object), or grey out the buttons for a script that is operating on a mesh object? I understand you could run a

self.report({'INFO'}, 'No Object Selected!')

in a execute function, but I already have an execute function for my Operator which is running fine when an object is selected. Basically I either need a grayed out button when no object is selected, or an error report telling the user to select an object first. I believe this might be possible with a Poll, but I don't know how to write it to check for an active object or not and print error to info, etc.

$\endgroup$

1 Answer 1

2
$\begingroup$

The poll function of your operator is suitable for this check indeed. Just let it check whether an object is selected/active in the current context and return a boolean:

import bpy

class HelloObjectOperator(bpy.types.Operator):
    bl_idname = "obj.hello"
    bl_label = "Minimal Object Operator"

    @classmethod
    def poll(cls, context):
        return context.object is not None

    def execute(self, context):
        print("Hello", context.object.name)
        return {'FINISHED'}

bpy.utils.register_class(HelloObjectOperator)

When adding your operator in a panel somewhere:

layout.operator("obj.hello")

The button will automatically grey out when no object is active.

$\endgroup$
4
  • 1
    $\begingroup$ Would go as far as to say this is the recommended way to go. Ensures your operator can't run (will throw a polling error) when (in this case) no active object. $\endgroup$
    – batFINGER
    Commented Jul 12, 2020 at 13:15
  • $\begingroup$ Awesome, thank you! This is probably a different question requiring a different post, but how would you have the Print run with the execute function that I already have coded (the buttons main function)? Would this be an if/else of some sort? So, if object is active/selected, execute the function, otherwise print("No Object Selected", context.object.name)?? $\endgroup$
    – Increality
    Commented Jul 12, 2020 at 18:21
  • 1
    $\begingroup$ When you want to do your check somewhere within the execution itself or in any other function which has the context or object information available, you could do: if context.object is not None: print("Hello", context.object.name) else: print("No Object Selected") $\endgroup$
    – Sighthound
    Commented Jul 12, 2020 at 18:53
  • 1
    $\begingroup$ Alternatively: if bpy.context.view_layer.objects.active: print("Hello", bpy.context.view_layer.objects.active.name) else: print("No object active"). Btw multiple objects might be selected, but only one object can be active. $\endgroup$
    – Sighthound
    Commented Jul 12, 2020 at 19:13

You must log in to answer this question.

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