Search code examples
pythonmayapyside2

How to add a eventFilter in Maya


I'd like to create an drag'n drop functionality with a custom Qt Window and Maya. From what I could find the only solution is to add a eventFilter for a Maya Widget. So this is what I tried to test it:

import maya.OpenMayaUI as omui
from PySide2 import QtWidgets
from PySide2 import QtCore
from shiboken2 import wrapInstance

def getMainWindowPtr():
    mayaMainWindowPtr = omui.MQtUtil.mainWindow()
    mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QtWidgets.QMainWindow)
    return mayaMainWindow

class FilterObject(QtCore.QObject):
    def eventFilter(self, obj, event):
        print "Event", obj, event, event.type()
        if event.type() == QtCore.QEvent.KeyPress:
            if not event.isAutoRepeat():
                key = event.key()
                print "Key", key
                if key == QtCore.Qt.Key_A:
                    print 'A held'
        return super(FilterObject, self).eventFilter(obj, event)

mainWin =  getMainWindowPtr()
mainWin.installEventFilter(FilterObject())

I'd expect to see a new line for every acton I do in Maya, but for some reason I do not see anything, no error no print message. So I suppose the event is not filtered or the event is taken away by another widget. Does someone has an idea how to approach this problem?


Solution

  • In PySide2 if the object is not assigned to a variable the GC deletes it, so in your case you must do the following:

    obj = FilterObject() 
    mainWin.installEventFilter(obj)