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, both QTableView
and QTreeView
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 the QHeaderView::sortIndicatorChanged() signal
to the QTableView::sortByColumn() slot
or the QTreeView::sortByColumn() slot
, respectively.
However, firstly the QTableView::sortByColumn()
is not a slot, so one cannot connect a signal to it; secondly, the code of QTableView::sortByColumn()
is something like
d->header->setSortIndicator(column, order);
//If sorting is not enabled, force to sort now.
if (!d->sortingEnabled)
d->model->sort(column, order);
and QHeaderView::setSortIndicator()
function emit sortIndicatorChanged(logicalIndex, order)
. But if one uses function setSortingEnabled(true)
, the signal sortIndicatorChanged(logicalIndex, order)
can also be emitted automatically by the view header when click the header column of the view.
So maybe the right way is to make a slot to receive the signal sortIndicatorChanged(logicalIndex, order)
and in the slot, call the override virtual function sort()
of 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(headerView, 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.