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__.

  1.  
  2. import bpy
  3.  
  4.  
  5. class EXAMPLE_addonPreferences(bpy.types.AddonPreferences):
  6. bl_idname = __package__
  7.  
  8. # Code below copied from https://b3d.interplanety.org/en/add-on-preferences-panel/
  9. add_bevel: bpy.props.EnumProperty(
  10. items=[
  11. ('bevel', 'Add bevel', '', '', 0),
  12. ('no_bevel', 'No bevel', '', '', 1)
  13. ],
  14. default='no_bevel'
  15. )
  16.  
  17. def draw(self, context):
  18. layout = self.layout
  19. layout.label(text='Add bevel modifier:')
  20. row = layout.row()
  21. row.prop(self, 'add_bevel', expand=True)
  22.  

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:

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

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