how to add a right click menu to each cell of QTableView in PyQt

爷,独闯天下 提交于 2019-11-28 19:43:33

QTableView has contextMenuEvent() event, to show a right-click menu:

  • Create a QMenu inside this event
  • Add some QActions to QMenu
  • connect each QAction to slots using triggered signal of QAction
  • call popup(QCursor.pos()) on QMenu

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)
...

I finally implemented it this way!!

def contextMenuEvent(self, pos):
    if self.selectionModel().selection().indexes():
        for i in self.selectionModel().selection().indexes():
            row, column = i.row(), i.column()
        menu = QtGui.QMenu()
        openAction = menu.addAction("Open")
        deleAction = menu.addAction("Delete")
        renaAction = menu.addAction("Rename")
        action = menu.exec_(self.mapToGlobal(pos))
        if action ==openAction:
            self.openAction(row, column)

def openAction(self, row, column):
    if self._slideShowWin:
        self._slideShowWin.showImageByPath(self._twoDLst[row][column])
        self._animateUpOpen()

def deleteSelected(self):
    # TODO
    pass

that works like a charm !!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!