I am trying to detect a key press in the middle of command execution in Python Maya. I first tried a brute-force approach using the QApplication event queue (probably not the optimal way):
class MyEventHandler(QtCore.QObject):
def eventFilter(self, qobj, event):
if event.type() == QtCore.QEvent.KeyPress:
print('key pressed')
return super(MyEventHandler, self).eventFilter(qobj, event)
class MyCmd(OpenMayaMPx.MPxCommand):
def __init__(self):
super().__init__()
self.maya_window = wrapInstance(int(OpenMayaUI.MQtUtil.mainWindow()), QtWidgets.QWidget)
self.event_handler = MyEventHandler()
self.app = QtWidgets.QApplication.instance()
self.app.installEventFilter(self.event_handler)
def __del__(self):
if hasattr(self, 'app'):
self.app.removeEventFilter(self.event_handler)
def doIt(self, args):
// do some stuff
QtWidgets.QApplication.processEvents()
// do some stuff
So while the command is being executed I see the event handler is being called with various message types but key press events are not detected at all, despite the fact I am pressing keys randomly during command execution. Any ideas why key presses are not being received using the code above?
Or is there a better way of achieving this, without using the application event queue?