Override context for operator called from panel

I have an operator, “my_operator”, that is called from a panel, as follows:

class CATEGORY_PT_test_panel(bpy.types.Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "Test"
    bl_context = "objectmode"
    bl_category = "Test"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        
        row = layout.row()
        row.operator('object.my_operator', text='Activate')

def menu_draw(self, context):
    self.layout.separator()
    self.layout.my_operator("object.my_operator")

This works fine, but I need to override the context when calling the operator; I need it to run in the context of the Image Editor. The only way I have found that works is to create a dummy operator (that is called from the panel) and in the dummy call “my_operator” as follows:

class OBJECT_OT_dummy(bpy.types.Operator):
    """Dummy operator workaround used for override."""     

    bl_idname = "object.dummy"     
    bl_label = "Dummy"         
    bl_options = {'REGISTER'}

    def execute(self, context):
        screen = context.screen
        override = bpy.context.copy()
        
        # Update the context 
        for area in screen.areas:
            if area.type == 'IMAGE_EDITOR':
                for region in area.regions:
                    if region.type == 'WINDOW':
                        override = {'region': region, 'area': area}
        
        bpy.ops.object.my_operator(override, 'INVOKE_DEFAULT')
        return {'FINISHED'}

Is there some better way to do this…? “my_operator” is modal for doing some stuff when the user clicks on the image in the Image Editor. I’m using Blender 2.8.

1 Like