[Solved]T he description about sorting in Model/View Qt document maybe wrong?
-
In Qt document online Model/View Programming, it's said that If your model is sortable, i.e, if it reimplements the
QAbstractItemModel::sort()
function, bothQTableView
andQTreeView
provide an API that allows you to sort your model data programmatically. In addition, you can enable interactive sorting (i.e. allowing the users to sort the data by clicking the view's headers), by connecting theQHeaderView::sortIndicatorChanged()
signal to theQTableView::sortByColumn() slot
or theQTreeView::sortByColumn() slot
, respectively.
However, firstly theQTableView::sortByColumn()
is not a slot, so one cannot connect a signal to it; secondly, the code ofQTableView::sortByColumn()
is something liked->header->setSortIndicator(column, order); //If sorting is not enabled, force to sort now. if (!d->sortingEnabled) d->model->sort(column, order);
and in
QHeaderView::setSortIndicator()
functionemit sortIndicatorChanged(logicalIndex, order);
but if uses functionsetSortingEnabled(true)
inQTreeView
, the signalsortIndicatorChanged(logicalIndex, order);
can also be emitted automatically.So maybe the right way is to make a slot to receive the signal
sortIndicatorChanged(logicalIndex, order);
of the header, and in the slot, call the override virtual functionsort()
in the model. -
Sort the tree view by click a column.
-
Set the view can be sorted by click the "header".
treeView_->setSortingEnabled(true);
-
Connect the header signal to a slot made by you.
connect(treeView_->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), treeModel_, SLOT(sortByColumn(int, Qt::SortOrder)));
-
In the slot, call the sort() virtual function of the model. sort() virtual function is a virtual function of QAbstractItemModel, and one should override it.
void TreeModel::sortByColumn(int column, Qt::SortOrder order) { sort(column, order); }
-
Override the sort() function as your model should do.
-
emit dataChanged(QModelIndex(), QModelIndex());
from a model to update the whole tree view.
-