如何获得QTableView右键单击索引

时间:2018-02-04 00:28:11

标签: python qt pyqt pyqt5

下面的代码会创建一个带有QTableView视图的对话框。 左键单击onLeftClick函数获取QModelIndex index。 稍后使用此QModelIndex打印左键单元格的行号和列号。

如何获取右键单击的单元格的QModelIndex索引?

enter image description here

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 个答案:

答案 0 :(得分:1)

您必须使用indexAt()QAbstractScrollArea)的QTableView方法:

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