How do you add a listener to a button? I need to handle something in the panel once a button is clicked but I don't know how to add this click event listener.
import bpy
class SimplePanel(bpy.types.Panel):
def on_button_click(self, context):
print("button clicked")
def draw(self, context):
layout = self.layout
row = layout.row()
op = row.operator("object.simple_operator")
op.add_click_listener(on_button_click) #FIXME
If I add a callback setter function in my operator like
def set_exec_callback(self, callback):
self.exec_callback = callback
and then do:
op.set_exec_callback(on_click)
It mistakenly tells me that
AttributeError: 'OBJECT_OT_my_operator' object has no attribute 'set_exec_callback'
even though it is clearly defined in my operator
Here's a script that reproduces the bug:
import bpy
class SimpleOperator(bpy.types.Operator):
bl_idname = "object.simple_operator"
bl_label = "Simple Operator"
def __init__(self):
self.callback = None
def set_callback(self, callback):
self.callback = callback
def execute(self, context):
self.callback()
return {'FINISHED'}
def my_callback():
print("Callback function called")
class TestPanel(bpy.types.Panel):
bl_label = "Test Panel"
bl_idname = "PT_TestPanel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Test'
def draw(self, context):
layout = self.layout
op = layout.operator(SimpleOperator.bl_idname, text="Execute Simple Operator")
op.set_callback(my_callback) # AttributeError: 'OBJECT_OT_simple_operator' object has no attribute 'set_callback'
def register():
bpy.utils.register_class(SimpleOperator)
bpy.utils.register_class(TestPanel)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
bpy.utils.unregister_class(TestPanel)
# Test the panel
if __name__ == "__main__":
register()