Well, some time ago I decided to go with PySide code for all my UIs instead of native maya.cmds functions for menu-building. I was attracted to the freedom in creating and styling of those menus, and the fact that Jeremy Ernst did a lot of menus with PySide. And another fact that knowing PySide I can not only write UIs for maya, but also for different standalone python tools. Which is cool. But if you just need a menu – go with cmds. Don’t bother with PySide.
Anyway, with that said, I still prefer to use PySide. And recently I was banging my head against the wall, trying to add a simple context menu to QLineEdit. To allow pasting some preset text into QLineEdit, for BroSelector tool.
And Finally, it worked!
Here is the full code related to it. I skip imports and window creation. Just the relevant stuff.
#Creating the actual QLineEdit. I use from QtGui import *, so I don't need to write QtGui.QLineEdit, just QLineEdit, mind that. self.type = QLineEdit("transform") # Adding context menu to line edit # Creating action. Make as many as you like self.actionHello = QAction(self) self.actionHello.setText("Hello") self.actionHello.triggered.connect(yourFunctionHere) # Creating Menu self.menu = QMenu(self) # Adding action to menu. Add as many as you like self.menu.addAction(self.actionHello) # First we need to change our element's Context Menu Policy to Custom. self.type.setContextMenuPolicy(Qt.CustomContextMenu) # Now we catch basically the right-click event, the customContextMenuRequested event, and assing our own handler (function) for it. self.type.customContextMenuRequested.connect(self.contextMenuRequested) #And here goes the handler function. def contextMenuRequested(self, point): # the point variable (which you can call whatever you like actually) is passed to this function as first arg, so we can use it in the next line. self.menu.exec_(self.type.mapToGlobal(point))
And thats it. YAY! Saving it here, so I won’t lose it, and in case it is useful to someone.
Copied from my site's blog: http://nixes.ru/?p=657