How to add user preferences for a Blender Add-on

When trying to implement user preferences for a 2.80 Blender add-on the official documentation was confusing for me and it didn't work with their example code. Their comment on what to set bl_idname as was the confusing part. Probably because of my Python inexperience.
https://docs.blender.org/api/current/bpy.types.AddonPreferences.html

After some searching I found this article that helped me understand what I had done wrong and make it work.
https://b3d.interplanety.org/en/add-on-preferences-panel/

Example code with preferences in own file

The code to get add-on preferences in Blender 2.80 in its own file was this code below. bl_idname should be __name__ if the class is inside __init__.py otherwise __package__.


import bpy


class EXAMPLE_addonPreferences(bpy.types.AddonPreferences):
    bl_idname = __package__

    # Code below copied from https://b3d.interplanety.org/en/add-on-preferences-panel/
    add_bevel: bpy.props.EnumProperty(
        items=[
            ('bevel', 'Add bevel', '', '', 0),
            ('no_bevel', 'No bevel', '', '', 1)
        ],
        default='no_bevel'
    )

    def draw(self, context):
        layout = self.layout
        layout.label(text='Add bevel modifier:')
        row = layout.row()
        row.prop(self, 'add_bevel', expand=True)


Here is an image of the add-on preferences UI from the code above.

How to use

To get the add-on preferences I used this code:


    # This part has changed from 2.79 -> 2.80, it used to be context.user_preference
    preferences = context.preferences
    # Use __name__ instead if inside the __init__.py file.
    addon_prefs = preferences.addons[__package__].preferences
    add_bevel = addon_prefs.add_bevel


The blender api change log can be found here:
https://docs.blender.org/api/current/change_log.html

More reading

Other Blender Add-on related blog posts by me that may be of interest:

No comments:

Post a Comment