I have an integer property I would like to increment as 2^int property. If that isn't possible, I would alternatively like to just have regular increment, but display the value in the panel as 2^property.
2 Answers
Here's a trick you can use. Incrementing will continue to adjust by ±1, but we'll give the prop a custom setter that snaps it to a power of 2. If the value decreased, we'll snap to the next lower one; if it increased, to the next higher one.
import bpy
def set_prop(self, value):
cur_value = self.power_of_2_prop
value = max(value, 1)
power_of_2 = 1 << (value.bit_length() - 1) # rounded down to power of 2
if value != power_of_2:
value = power_of_2 if value < cur_value else 2 * power_of_2
self["power_of_2_prop"] = value
# Note: This is the default getter, but the setter won't
# work unless we provide it too for some reason.
def get_prop(self):
return self.get("power_of_2_prop", 1)
bpy.types.Scene.power_of_2_prop = bpy.props.IntProperty(get=get_prop, set=set_prop)
# Add panel in the Properties Editor to test it
class LayoutDemoPanel(bpy.types.Panel):
"""Creates a Panel in the scene context of the properties editor"""
bl_label = "Test Panel"
bl_idname = "SCENE_PT_layout"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "scene"
def draw(self, context):
layout = self.layout
scene = context.scene
layout.prop(scene, "power_of_2_prop")
bpy.utils.register_class(LayoutDemoPanel)
Look for the Test Panel in the Scene tab of the Properties Editor.
@scurest's answer is definitely works as an answer for the first, however I think I'll use this approach because the interaction of setting a number and then it snapping to the nearest power is a bit wonky.
I was able to figure out the second approach, where it just shows 2 to the power of the property alongside the power, using the following expression:
col.prop(Rprops,'resolution', text='Resolution: '+str(2**Rprops.resolution))