Custom Python callback from plug-in

Custom Python callback from plug-in

negow
Advocate Advocate
2,015 Views
2 Replies
Message 1 of 3

Custom Python callback from plug-in

negow
Advocate
Advocate

Hi all,

 

There are native callbacks for listening on node creation or attribute changes, such as MNodeMessage and MSceneMessage. For example..

 

from maya.api import MDGMessage

def on_joint_added(mobj, clientData):
  print("%s was added" % mobj)

MDGMessage.addNodeAddedCallback(on_joint_added, "joint")

 

..but how do I emit my own event, from my own custom plug-in?

 

For example, I'd like for a Python command to get called whenever my plug-in is under duress.

from my_api

def on_plugin_struggling(message):
  print(message)

my_api.addCallbackOnDuress(on_plugin_struggling)

 

I noticed MPluginCallableInfo along with members of MMessage which seem relevant, namely setRegisteringCallableScript. But I can't quite piece together how to actually use these, especially without examples.

 

Is this possible? The alternative I'm looking at is building a Python binding for my plug-in, and passing in a callback that way. But C-extensions for Maya's embedded Python interpreter has proven a lot more challenging than I would have liked.. https://github.com/mottosso/maya_python_c_extension/issues

 

Accepted solutions (1)
2,016 Views
2 Replies
Replies (2)
Message 2 of 3

bradley_henke
Enthusiast
Enthusiast
Accepted solution

Maybe you could use MUserEventMessage?

 

It looks like the sequence of events is:

  1. Register the new user event
  2. Add callbacks for when the event is called. In your case `on_plugin_struggling`
  3. Have your plugin post the event whenever it is struggling.

 

import maya.api.OpenMaya as om

# This registration would happen at the same time that your plugin is registered
om.MUserEventMessage.registerUserEvent('strugglingEvent')

# Define your callback
def struggleCallback(clientData=None):
    print('Im Struggling')

# Add the callback to the list of functions which should execute when your plugin event is posted
eventId = om.MUserEventMessage.addUserEventCallback('strugglingEvent', struggleCallback)

# When your plugin is struggling, have the plugin post the event
om.MUserEventMessage.postUserEvent('strugglingEvent')

# When you unload your plugin, remove the callbacks and deregister the event
om.MUserEventMessage.removeCallback(eventId)
om.MUserEventMessage.deregisterUserEvent('strugglingEvent')

 

Message 3 of 3

negow
Advocate
Advocate

This is exactly what I was looking for, thank you!

0 Likes