我有一个带有单元格的QTableView,我在其上设置了1,2和4的列跨度。我正在努力使它在选择单元格时,它上面的所有单元格也会自动选中,因此在下面的示例中单击x
会选择所有这些细胞:
我尝试通过循环遍历所有选定的索引,并选择上面一行的单元格来做到这一点,但是,如果选择最左边的索引,它似乎只选择跨越多列的单元格。在我的例子中,选择索引(1,1)或索引(0,2)什么都不做。所以我需要能够选择给定细胞跨越的任何索引的细胞。我怎样才能做到这一点?例如,给定索引(0,2)或索引(0,3)这些都是列跨度为4的相同单元格,我如何以编程方式确定此单元格从索引(0,0)开始
你必须在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_())