Example of Dynamic Popup Menus
'''
Author: Carlo Cherisier
Date: 08.25.15
Script: ZeroOut
import ZeroOut
reload(ZeroOut)
ZeroOut.show_dialog()
'''
import sys
import functools
from PySide import QtCore, QtGui
class TestUI(QtGui.QDialog):
def __init__(self, *args, **kws):
parent = kws.get('parent', None)
super(TestUI, self).__init__(parent=parent)
## Class variables
self.mapper = QtCore.QSignalMapper(self)
## Setup GUI
self.createWindow()
self.setupConnections()
def createWindow(self):
'''
Purpose: Contains all window elements
'''
## Font Variable
# fontSize = QtGui.QFont()
## Window Title
self.setWindowTitle('Zero Out')
## Main Layout
self._mainLayout = QtGui.QVBoxLayout()
self._mainLayout.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(self._mainLayout)
self.thisButton = QtGui.QPushButton('This Button')
self._mainLayout.addWidget(self.thisButton)
def _createPopup(self, widget, func, args):
## Enable Right
widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
widget.customContextMenuRequested.connect(func)
## Create Popup Menu
thisMenu = QtGui.QMenu(self)
for each in args:
label = 'Zero Out {0}'.format(each)
## You can also use partial to achieve this instead of mapping
# thisMenu.addAction(label, functools.partial(func2, each))
action = QtGui.QAction(label, self)
self.mapper.setMapping(action, each)
action.triggered.connect(self.mapper.map)
thisMenu.addAction(action)
return thisMenu
def setupConnections(self):
'''
Purpose: Connect all GUI Elemenents to functions
'''
self.thisButton.clicked.connect(self.thisButton_clicked)
args = ['RX', 'RY', 'RZ']
self.thisButton_Popup = self._createPopup(self.thisButton, self.showthisButton_Popup, args)
self.mapper.mapped['QString'].connect(self.doSomethingCool)
def showthisButton_Popup(self, point):
'''
Show Popup Menu on Rotation QPushButton
'''
self.thisButton_Popup.exec_(self.thisButton.mapToGlobal(point))
def doSomethingCool(self, arg):
if(arg == 'RX'):
print 'RX'
elif(arg == 'RY'):
print 'RY'
elif(arg == 'RZ'):
print 'RZ'
def thisButton_clicked(self):
print 'Button Clicked'
def main():
global test
try:
test.deleteLater()
except:
pass
try:
app = QtGui.QApplication(sys.argv)
test = TestUI()
test.show()
sys.exit(app.exec_())
except(RuntimeError):
test = TestUI()
test.show()
if __name__ == '__main__':
main()