To display an icon next to a property, text label, or on the operator button in the UI, we need to specify its identifier in the “icon” or “icon_value” parameter. But not all types of icons have their identifiers known in advance. For example, we cannot predefine the icon’s identifiers for procedural textures and materials because they are generated at runtime.
To get the identifier of such a dynamic icon, we can use the “icon” method of the “UILayout” class.
We can access the “UILayout” class inside the “draw” function with the “self.layout” pointer.
For example, let’s define a class that creates a custom subpanel in the N-panel of the 3D Viewport window, and display a list of all scene materials with their icons on it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import bpy from bpy.types import Panel from bpy.utils import register_class class MATLIST_PT_panel(Panel): bl_idname = 'MATLIST_PT_panel' bl_label = 'Materials List' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Materials List' def draw(self, context): layout = self.layout register_class(MATLIST_PT_panel) |
In the “draw” function, we set the “layout” variable with the “UILayout” class pointer.
Next, to display all the scene materials on our panel, let’s cycle through their list, creating a text label for each one.
1 2 |
for mat in bpy.data.materials: layout.label(text=mat.name) |
Near the material name let’s display its icon.
We can get the material icon identifier through the “icon” method, specifying the current material in its parameter.
1 |
layout.icon(mat) |
Add the received icon identifier to the “icon_value” parameter when creating a text label with the material name.
1 2 |
for mat in bpy.data.materials: layout.label(text=mat.name, icon_value=layout.icon(mat)) |
Now the material icon will be shown with the material name.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import bpy from bpy.types import Panel from bpy.utils import register_class class MATLIST_PT_panel(Panel): bl_idname = 'MATLIST_PT_panel' bl_label = 'Materials List' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Materials List' def draw(self, context): layout = self.layout for mat in bpy.data.materials: layout.label(text=mat.name, icon_value=layout.icon(mat)) register_class(MATLIST_PT_panel) |
*.blend file with sample code for my Patreon subscribers.