本文介紹了如何獲取 QTableView 右鍵單擊??索引的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
下面的代碼創建了一個帶有 QTableView
視圖的對話框.左鍵單擊 onLeftClick
函數會獲得一個 QModelIndex index
.此 QModelIndex 稍后用于打印左鍵單擊單元格的行號和列號.
The code below creates a single dialog with a QTableView
view.
On left-click the onLeftClick
function gets an QModelIndex index
.
This QModelIndex is used later to print the row and column numbers of the left-clicked cell.
如何獲取被右鍵單擊的單元格的QModelIndex
索引?
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_()
推薦答案
你必須使用 QAbstractScrollArea
(QTableView
的 indexAt()
方法代碼>):
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()))
這篇關于如何獲取 QTableView 右鍵單擊??索引的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!