How to get QTableView right clicked index

感情迁移 提交于 2020-06-23 09:51:32

问题


The code below creates a single dialog with a QTableView view. On left-click the onLeftClickfunction gets an QModelIndex index. This QModelIndex is used later to print the row and column numbers of the left-clicked cell.

How to get the QModelIndex index of the cell that was right-clicked?

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
app = QApplication([])


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.view = QTableView(self)
        self.view.setSelectionBehavior(QTableWidget.SelectRows)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.onRightClick)
        self.view.clicked.connect(self.onLeftClick)

        self.view.setModel(QStandardItemModel(4, 4))
        for each in [(row, col, QStandardItem('item %s_%s' % (row, col))) for row in range(4) for col in range(4)]:
            self.view.model().setItem(*each)

        self.layout().addWidget(self.view)
        self.resize(500, 250)
        self.show()

    def onRightClick(self, qPoint):
        sender = self.sender()
        for index in self.view.selectedIndexes():
            print 'onRightClick selected index.row: %s, selected index.column: %s' % (index.row(), index.column())

    def onLeftClick(self, index):
        print 'onClick index.row: %s, index.row: %s' % (index.row(), index.column())


dialog = Dialog()
app.exec_()

回答1:


You have to use the indexAt() method of the QAbstractScrollArea (QTableView):

def onRightClick(self, qPoint):
    index = self.view.indexAt(qPoint)
    if index.isValid():
        print('onClick index.row: %s, index.col: %s' % (index.row(), index.column()))


来源:https://stackoverflow.com/questions/48603517/how-to-get-qtableview-right-clicked-index

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