Ever miss Maya’s popupMenu Command? Simple Right-Click Menus in PySide/PyQt?
So I’ve recently switched to starting to do interfaces in Qt, and one thing that annoyed me that I was missing from my old maya command scripting days was a simple single command to create a right-click menu. A lot of the solutions I found online seemed a little weird, involving creating the entire menu as part of a command run when you right-click. I dunno, maybe it’s because I was just used to creating the menu and having it behave like any other menu when adding menuItems (or in this case, actions)
Anyways, I was starting to try and do something complicated, but realized I could just do it in a few lines to get what I wanted. By the way, this works with PySide and Qt4 unadulterated (at least it did for me)
class RightClickMenu(QtGui.QMenu): def __init__(self, *args, **kwargs): super(RightClickMenu, self).__init__(*args) # Prepare the parent widget for using the right-click menu self.parentWidget().setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.parentWidget().customContextMenuRequested.connect(self.showMenu) def showMenu(self, *args): self.exec_(QtGui.QCursor.pos())
So all you’d have to do to implement it is like any other menu:
wid = QtGui.QWidget() ppup = RightClickMenu(wid) ppup.addAction('Testing') ppup.addAction('Testing...') ppup.addAction('123') wid.show()
This might be common knowledge, but I couldn’t find it out there before, so maybe it will help any other Qt newbs like me that may run in to the problem. But now I can have it sitting in a module ready to go whenever I need it.
Pro-users, if there’s some red flag I’m not spotting, let me know as well.