[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, 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 in QHeaderView::setSortIndicator() function emit sortIndicatorChanged(logicalIndex, order); but if uses function setSortingEnabled(true) in QTreeView, the signal sortIndicatorChanged(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 function sort() in the model.



  • It seems you're right.

    Maybe the explanation is not perfect.



  • Sort the tree view by click a column.

    1. Set the view can be sorted by click the "header".

       treeView_->setSortingEnabled(true);
      
    2. Connect the header signal to a slot made by you.

       connect(treeView_->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)),
           treeModel_, SLOT(sortByColumn(int, Qt::SortOrder)));
      
    3. 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);
       }
      
    4. Override the sort() function as your model should do.

    5. emit dataChanged(QModelIndex(), QModelIndex());from a model to update the whole tree view.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.