QTableView
has contextMenuEvent()
event, to show a right-click menu:
- Create a
QMenu
inside this event - Add some
QAction
s toQMenu
- connect each
QAction
to slots usingtriggered
signal ofQAction
- call
popup(QCursor.pos())
onQMenu
When user right-click the tableView the cell under the mouse pointer will be selected and at the same time a menu will appear. When user selects an action on the menu, the connected slot will be called, get the selected cell of tabel in this slot and perform the required action on this cell.
...
def contextMenuEvent(self, event):
self.menu = QtGui.QMenu(self)
renameAction = QtGui.QAction('Rename', self)
renameAction.triggered.connect(lambda: self.renameSlot(event))
self.menu.addAction(renameAction)
# add other required actions
self.menu.popup(QtGui.QCursor.pos())
...
def renameSlot(self, event):
print "renaming slot called"
# get the selected row and column
row = self.tableWidget.rowAt(event.pos().y())
col = self.tableWidget.columnAt(event.pos().x())
# get the selected cell
cell = self.tableWidget.item(row, col)
# get the text inside selected cell (if any)
cellText = cell.text()
# get the widget inside selected cell (if any)
widget = self.tableWidget.cellWidget(row, col)
...