10
$\begingroup$

How would I know through a script when the switch to edit mode happens? I need it for modal operator.

I was thinking on listening for 'TAB' event and checking obj.mode, but I hope there is a better way, for reasons like changed edit-mode shortcut or switching to edit-mode by script.

$\endgroup$

3 Answers 3

10
$\begingroup$

In your modal operator you can test object.mode for which mode the object is in - example:

import bpy

bpy.context.active_object.mode   # = 'OBJECT'

bpy.ops.object.mode_set(mode='EDIT')

bpy.context.active_object.mode   # = 'EDIT'

There is no callback, you will need to test this on 'tab' event or always to be sure..

$\endgroup$
1
  • $\begingroup$ Alternatively, you can check bpy.context.mode which will be EDIT_MESH if in edit mode $\endgroup$
    – Justin
    May 17, 2020 at 20:43
4
$\begingroup$

There is no way to "trigger" your script when the user enters edit mode. The only way for you to run your own code on entering edit mode is to set the keyboard shortcuts to run your script instead of changing to edit mode.

As it sounds like you are referring to switching to edit mode while your modal operator is running, you will need to check the event and enter edit mode when the tab key is pressed, other operators will not be run while your modal operator is running.

def modal(self, context, event):
    if event.type == 'TAB':
        if context.active_object.mode == 'EDIT':
            bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
        else:
            bpy.ops.object.mode_set(mode='EDIT', toggle=False)
$\endgroup$
1
  • 3
    $\begingroup$ other operators will be run if the modal returns {'PASS_THROUGH'} $\endgroup$ Dec 26, 2014 at 20:14
4
$\begingroup$

In 2.8, you can use message bus to do that:

The principle is to obtain the path using a path name through the object.

Then declare a subscription to message bus.

import bpy

#The callback when then change occurs
def a_callback(object, data):
    print( object, data, "changed" )

def subscribe_to(object,data_path,callback):

    #Get a rna subscription link from the object
    subscribe_to = object.path_resolve(data_path, False)

    #Effectively subscribe to the rna path from the object
    bpy.msgbus.subscribe_rna(
        key=subscribe_to,
        owner=object,
        args=(object,data_path,),
        notify=callback,
    )

subscribe_to(bpy.context.object,"mode", a_callback)

Note: bpy.msgbus is not documented for now. But it contains few functions that we can find using the Python console:

enter image description here

$\endgroup$
2
  • $\begingroup$ Or via context.mode? $\endgroup$
    – batFINGER
    Mar 10, 2020 at 11:36
  • $\begingroup$ @batFINGER, is it supported? $\endgroup$
    – lemon
    Mar 10, 2020 at 11:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .