When making your own custom operators, sometimes it is necessary to pass them certain values – execute operator with parameters.
The passed parameter must be defined as an operator property.
Let’s write a simple operator class to print a text value, passed to it through the parameter.
Define an operator class:
1 2 3 4 |
class TestOperator(bpy.types.Operator): bl_idname = 'test.operator' bl_label = 'test' |
Add a string property with the “text” name:
1 2 3 4 |
text: bpy.props.StringProperty( name = 'text', default = '' ) |
And define an “execute” function to run when the operator is called:
1 2 3 |
def execute(self, context): print(self.text) return {'FINISHED'} |
This function prints the value of the “text” property, which we will pass as a parameter when calling an operator.
Register an operator:
1 2 3 4 5 6 |
def register(): bpy.utils.register_class(TestOperator) if __name__ == '__main__': register() |
Complete text:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import bpy class TestOperator(bpy.types.Operator): bl_idname = 'test.operator' bl_label = 'test' text: bpy.props.StringProperty( name = 'text', default = '' ) def execute(self, context): print(self.text) return {'FINISHED'} def register(): bpy.utils.register_class(TestOperator) if __name__ == '__main__': register() |
After an operator registration we can call it with passing some text through the “text” parameter:
1 2 3 |
bpy.ops.test.operator(text='Hello World!') # Hello World! |
If we call our operator by pressing a button on the UI panel its parameter passes as follows:
1 2 |
button = self.layout.operator('test.operator', text='Execute') button.text = 'Hello World!' |