سؤال

I'm trying to select two columns of QTableView in code. Unfortunatelly, when I call

tableView->selectColumn(1)
tableView->selectColumn(2)

it selects 1st column, deselects 1st column and selects 2nd column. Is it possible to select multiple columns in code?

هل كانت مفيدة؟

المحلول

If you just need to ensure to allow the user to select multiple columns, you need to set up the proper selection mode as follows:

tableView->setSelectionMode(QAbstractItemView::MultiSelection);

If you would like to do this programatically, this is the way of doing it:

QModelIndexList itemSelection = tableView->selectionModel()->selectedColumns();
int currentColumn = itemSelection.first().column();
QItemSelection selectedItems = tableView->selectionModel()->selection();

tableView->selectColumn(1);
selectedItems.merge(tableView->selectionModel()->selection(), QItemSelectionModel::Select);
tableView->selectColumn(2);
selectedItems.merge(tableView->selectionModel()->selection(), QItemSelectionModel::Select);

tableView->selectionModel()->clearSelection();
tableView->selectionModel()->select(selectedItems, QItemSelectionModel::Select);

Disclaimer: the code has been taken from here, and then modified to suit your need.

نصائح أخرى

selectionModel.select() in its select columns mode may be preferable.

In PyQt:

columns = [1,2,3]
indexes = [model.index(0, c) for c in columns]
mode = QtCore.QItemSelectionModel.Select | QtCore.QItemSelectionModel.Columns
[tableView.selectionModel().select(index, mode) for i in indexes]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top