4

With:

tableView = QTableView()
rows = [0, 1, 2]

tableView.selectRow(0) or tableView.selectRow(2) won't work in this situation since selectRow() selects only single row deselecting all others.

There is selectionModel().select() method available. But it accepts QSelectionItems object as the argument. How do we declare the QSelectionItem object having the row numbers?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

3 Answers3

8

You should set the selection mode.

tableView->setSelectionMode(QAbstractItemView::MultiSelection);
Onur Tuna
  • 1,030
  • 1
  • 10
  • 28
  • 1
    Thanks! With the selection mode set to `MultiSelection` what command needs to be used to select row 0 and row 2 so both rows are selected at the same? – alphanumeric May 04 '16 at 20:38
  • 1
    It depends on how you implement. The user will be able to select both at the same time. Try tableView->setSelectionBehavior(QAbstractItemView::SelectItems); – Onur Tuna May 04 '16 at 20:45
  • 2
    Thanks again! I would like to know how to select multiple items in QTableView from inside of function (code) (not from the user interaction). Sorry for not being clear. – alphanumeric May 04 '16 at 22:31
5

The code creates a QTableView and QPushButton. Pressing the button selects the indexes in continuous order (from index1 to index2. It is still an unswered question if it would be possible to select the indexes in any order.

enter image description here

def clicked():
    tableView.setFocus()
    selectionModel = tableView.selectionModel()
    index1 = tableView.model().index(0, 0)
    index2 = tableView.model().index(1, 2)
    itemSelection = QtGui.QItemSelection(index1, index2)
    selectionModel.select(itemSelection, QtGui.QItemSelectionModel.Rows | QtGui.QItemSelectionModel.Select)

app = QtGui.QApplication([])
window = QtGui.QWidget()
window.resize(400, 300)
tableView = QtGui.QTableView()

model = QtGui.QStandardItemModel(4, 2)
for row in range(0, 4):
    for column in range(0, 3):
        item = QtGui.QStandardItem("%s , %s"%(row, column))
        model.setItem(row, column, item)

tableView.setModel(model)

selectionModel = QtGui.QItemSelectionModel(model)
tableView.setSelectionModel(selectionModel)

button = QtGui.QPushButton('Select from 0,0 to 1,2')
button.clicked.connect(clicked)
layout = QtGui.QVBoxLayout()
layout.addWidget(tableView)
layout.addWidget(button)
window.setLayout(layout)
window.show()

app.exec_()
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
2

select() can also accept an index (and a mode of select rows), so you can do this:

rows = [1,2,3]
indexes = [model.index(r, 0) for r in rows]
mode = QtCore.QItemSelectionModel.Select | QtCore.QItemSelectionModel.Rows
[tableView.selectionModel().select(index, mode) for i in indexes]
dave
  • 572
  • 7
  • 16