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

前端 未结 2 433
说谎
说谎 2020-12-08 08:38

I want to add a right click menu to delete, rename or open image in each of cell of QTAbleView in the rigt click menu, I have tried and found everyone is trying to add menu

相关标签:
2条回答
  • 2020-12-08 08:52

    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 !!!

    0 讨论(0)
  • 2020-12-08 09:01

    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)
    ...
    
    0 讨论(0)
提交回复
热议问题