ui_previews_custom_icon.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # This sample script demonstrates how to place a custom icon on a button or
  2. # menu entry.
  3. #
  4. # IMPORTANT NOTE: if you run this sample, there will be no icon in the button
  5. # You need to replace the image path with a real existing one.
  6. # For distributable scripts, it is recommended to place the icons inside the
  7. # addon folder and access it relative to the py script file for portability
  8. #
  9. #
  10. # Other use cases for UI-previews:
  11. # - provide a fixed list of previews to select from
  12. # - provide a dynamic list of preview (eg. calculated from reading a directory)
  13. #
  14. # For the above use cases, see the template 'ui_previews_dynamic_enum.py"
  15. import os
  16. import bpy
  17. class PreviewsExamplePanel(bpy.types.Panel):
  18. """Creates a Panel in the Object properties window"""
  19. bl_label = "Previews Example Panel"
  20. bl_idname = "OBJECT_PT_previews"
  21. bl_space_type = 'PROPERTIES'
  22. bl_region_type = 'WINDOW'
  23. bl_context = "object"
  24. def draw(self, context):
  25. layout = self.layout
  26. pcoll = preview_collections["main"]
  27. row = layout.row()
  28. my_icon = pcoll["my_icon"]
  29. row.operator("render.render", icon_value=my_icon.icon_id)
  30. # my_icon.icon_id can be used in any UI function that accepts
  31. # icon_value # try also setting text=""
  32. # to get an icon only operator button
  33. # We can store multiple preview collections here,
  34. # however in this example we only store "main"
  35. preview_collections = {}
  36. def register():
  37. # Note that preview collections returned by bpy.utils.previews
  38. # are regular py objects - you can use them to store custom data.
  39. import bpy.utils.previews
  40. pcoll = bpy.utils.previews.new()
  41. # path to the folder where the icon is
  42. # the path is calculated relative to this py file inside the addon folder
  43. my_icons_dir = os.path.join(os.path.dirname(__file__), "icons")
  44. # load a preview thumbnail of a file and store in the previews collection
  45. pcoll.load("my_icon", os.path.join(my_icons_dir, "icon-image.png"), 'IMAGE')
  46. preview_collections["main"] = pcoll
  47. bpy.utils.register_class(PreviewsExamplePanel)
  48. def unregister():
  49. for pcoll in preview_collections.values():
  50. bpy.utils.previews.remove(pcoll)
  51. preview_collections.clear()
  52. bpy.utils.unregister_class(PreviewsExamplePanel)
  53. if __name__ == "__main__":
  54. register()