Search code examples
user-interfaceblenderbpy

Blender - Inserting a text button using bpy


I'm designing a simple GUI for a Blender 2.80 plug-in. I've created a dialog box to enter some data:

enter image description here

I would like to replace the line of text ("Lorem ipsum ...") with a button with a custom label (example "click here to visit our website").

Below is the code I am using:

class ExportFDSCloudHPC(Operator):

    bl_idname = "..."
    bl_label = "Title"
    bl_description = "..."

    data1 = bpy.props.StringProperty(
        name = "Text 1",
        default = "..."
    )

    data2 = bpy.props.StringProperty(
        name = "Text 2",
        default = "..."
    )

    data3 = bpy.props.StringProperty(
        name = "Text 3",
        default = "..."
    )
    
    def draw(self, context):
        col = self.layout.column(align = True)
        col.prop(self, "data1")

        self.layout.label(text="Lorem ipsum dolor sit amet, consectetur adipisci elit...")

        col = self.layout.column(align = True)
        col.prop(self, "data2")

        col = self.layout.column(align = True)
        col.prop(self, "data3")

    def execute(self, context):
        ...

Solution

  • To get button you need to provide an existing operator: row.operator("wm.save_as_mainfile") button text is defined in operator. If you want to change name of existing operator use row.operator("wm.save_as_mainfile", text='My Save Label')

    You can create own operator:

    import bpy
    
    def main(context):
        for ob in context.scene.objects:
            print(ob)
    
    class SimpleOperator(bpy.types.Operator):
        """Tooltip"""
        bl_idname = "object.simple_operator" # <- put this string in layout.operator()
        bl_label = "Simple Object Operator" # <- button name
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            main(context)
            return {'FINISHED'}
    
    def register():
        bpy.utils.register_class(SimpleOperator)
    
    def unregister():
        bpy.utils.unregister_class(SimpleOperator)
        
    if __name__ == "__main__":
        register()
    
        # test call
        bpy.ops.object.simple_operator()
    

    and then use it like that:

    [..]
    col.prop(self, "data1")
    col.operator("object.simple_operator")
    # self.layout.label(text="Lorem ipsum dolor sit amet, consectetur adipisci elit...")
    
    col = self.layout.column(align = True)
    [..]