Note: This is an archived version of the Blender Developer Wiki (archived 2024). The current developer documentation is available on developer.blender.org/docs.

User:Sybren/SfA/operators

Your Own Operator

  • So far: only snippets of code.
  • Not really user friendly.
  • Menu items, buttons, panels.
  • For that: operators.

What is operator

  • Glue between some code and hotkeys, menus, buttons.
  • F3 to search for them.
  • Operator provides identifier, label, and tooltip.
  • Checks the context.
  • Multiple modes
    • execute: simplest, single-shot. This happens when you call from Python.
    • invoke: when called from UI, can do some extra things and then calls execute()
    • modal: needs to be set up from invoke, allows running for longer period (file browsers, exporters, network communication). Makes the operator receive events (keyboard presses, mouse moves, timers).

Making an operator

  • Group some information together:
    • Identifier (the thing after bpy.ops)
    • Label
    • Tooltip
    • The code itself
  • Make a class
    • Inheritance: parent-child structure
    • Just like in real life: child answers what it can, otherwise defers to parent: "Moooooom!"
    • The practical side: we can add what we need, and leave out what we don't.
  • Put the code into a function.
  • Add an execute method to call our function.
  • Register the operator.
  • Use F3 to find & run it.

Passing Parameters & the Redo Panel

  • Property: Number of monkeys
  • Set bl_options = {'REGISTER', 'UNDO'}
  • Use the redo panel

Limiting the Context

  • Show example of 'autocomplete' operator in 3D view and Python console.
  • Done by poll class method returning True or False
  • Make our operator only run when in 3D view:
@classmethod
def poll(cls, context) -> bool:
    return context.area.type == 'CONSOLE' and context.mode == 'OBJECT'