我有一个QTableView,其中的单元格我将列跨度设置为1、2和4。我试图创建它,以便在选择一个单元格时也自动选择其上方的所有单元格,因此在示例中在下面点击x
将会选择所有这些单元格:
我尝试通过仅遍历所有选定的索引并选择上方一行的单元格来执行此操作,但是似乎只有在选择了最左侧的索引时,才选择跨多列的单元格。在我的示例中,选择index(1,1)或index(0,2)不会执行任何操作。因此,我需要能够根据单元格跨度的任何索引来选择一个单元格。我怎样才能做到这一点?例如给定index(0,2)或index(0,3)这两个都是同一个单元格,列跨度为4,如何以编程方式确定此单元格从index(0,0)开始
答案 0 :(得分:2)
您必须在QAbstractItemView::MultiSelection
中将其设置为选择模式,并且必须通过将setSelection()
所属的矩形传递给QModelIndex
来使用它:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self._model = QtGui.QStandardItemModel(3, 8)
self._table = QtWidgets.QTableView(
selectionMode=QtWidgets.QAbstractItemView.MultiSelection,
clicked=self.on_clicked,
)
self._table.setModel(self._model)
self.fill_table()
self.setCentralWidget(self._table)
def fill_table(self):
data = [
('A', (0, 0), (1, 4)),
('B', (0, 4), (1, 4)),
('one', (1, 0), (1, 2)),
('two', (1, 2), (1, 2)),
('three', (1, 4), (1, 2)),
('four', (1, 6), (1, 2)),
('x', (2, 0), (1, 1)),
('y', (2, 1), (1, 1)),
('x', (2, 2), (1, 1)),
('y', (2, 3), (1, 1)),
('x', (2, 4), (1, 1)),
('y', (2, 5), (1, 1)),
('x', (2, 6), (1, 1)),
('y', (2, 7), (1, 1)),
]
for text, (r, c), (rs, cs) in data:
it = QtGui.QStandardItem(text)
self._model.setItem(r, c, it)
self._table.setSpan(r, c, rs, cs)
@QtCore.pyqtSlot('QModelIndex')
def on_clicked(self, ix):
self._table.clearSelection()
row, column = ix.row(), ix.column()
sm = self._table.selectionModel()
indexes = [ix]
for i in range(row):
ix = self._model.index(i, column)
indexes.append(ix)
for ix in indexes:
r = self._table.visualRect(ix)
self._table.setSelection(r, QtCore.QItemSelectionModel.Select)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())