One simple way is to add an if-statement to the body of the handler in order to determine whether the rest of the code should execute by using one additional Bool
or EnumProperty
declared in the preferences of your add-on:
class MYTOOL_AP_preferences(bpy.types.AddonPreferences):
...
state: bpy.props.BoolProperty(name="Switch")
...
def my_save_handler(dummy):
if state:
...
Demo on how the user can disable the handler via Preferences
using one EnumProperty
:
import bpy
bl_info = {"name": "Stats Add-on", "blender": (2, 82, 0), "category": "System"}
class MYTOOL_AP_preferences(bpy.types.AddonPreferences):
# this must match the add-on name, use '__package__'
# when defining this in a submodule of a python package.
bl_idname = __name__
state: bpy.props.EnumProperty(name="Switch", default = 'ON',
items=(("ON", "On", "", 1), ("OFF", "Off", "", 2)))
def draw(self, context):
self.layout.row().prop(self, "state", expand=True)
def my_save_handler(dummy):
if bpy.context.preferences.addons[__name__].preferences.state == 'ON':
print ("Blend file has been saved.")
def register():
bpy.utils.register_class(MYTOOL_AP_preferences)
bpy.app.handlers.save_post.append(my_save_handler)
def unregister():
bpy.app.handlers.save_post.remove(my_save_handler)
bpy.utils.unregister_class(MYTOOL_AP_preferences)
if __name__ == "__main__":
register()