Skip to content

Instantly share code, notes, and snippets.

@leixingyu
Created December 5, 2021 23:32
Show Gist options
  • Save leixingyu/74a242d46e06887cc1df426c417541c4 to your computer and use it in GitHub Desktop.
Save leixingyu/74a242d46e06887cc1df426c417541c4 to your computer and use it in GitHub Desktop.
class Demo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Demo, self).__init__(parent)
# initialization object
layout = QtWidgets.QGridLayout()
self.widget = QtWidgets.QListWidget()
layout.addWidget(self.widget)
self.setLayout(layout)
self.widget.addItem('item A')
self.widget.addItem('item B')
self.widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.widget.customContextMenuRequested.connect(self.openContextMenu)
self.widget.itemClicked.connect(lambda item: self.printThings(item))
def openContextMenu(self):
contextMenu = QtWidgets.QMenu()
# Enable options when only certain number of row is selected (typically one)
selectedIndexes = list(
set([item.row() for item in self.widget.selectedIndexes()]))
if len(selectedIndexes) == 1:
item = self.widget.currentItem()
# menu option
functionAction = contextMenu.addAction('Menu Text go here')
functionAction.triggered.connect(
lambda: self.execFunctionWithArgs(item))
# menu option with sub-menu
functionMenu = contextMenu.addMenu('More options here!')
submenu = functionMenu.addAction('Sub Menu here')
submenu.triggered.connect(lambda: self.execFunctionWithArgs(item))
else:
items = self.widget.selectedItems()
# Enable options for other senarios
anotherAction = contextMenu.addAction('Menu Text go here')
anotherAction.triggered.connect(self.execFunction)
cursor = QtGui.QCursor()
contextMenu.exec_(cursor.pos())
def execFunctionWithArgs(self, argument):
pass
def execFunction(self):
pass
def printThings(self, item):
print(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment