Sort QStandardItemModel in c++ Qt

Temirlan picture Temirlan · Apr 20, 2011 · Viewed 7.3k times · Source

I have a model of type QStandardItemModel which looks like this:

          QHash<int, QByteArray> roleNames;
          roleNames[Car2goVehicle::NameRole] =  "plate_number";
          roleNames[Car2goVehicle::DescriptionRole] = "address";
          roleNames[Car2goVehicle::FuelRole] = "fuel";
          roleNames[Car2goVehicle::InteriorRole] = "interior";
          roleNames[Car2goVehicle::ExteriorRole] = "exterior";
          roleNames[Car2goVehicle::VinRole] = "vin";
          roleNames[Car2goVehicle::LatRole] = "lat";
          roleNames[Car2goVehicle::LonRole] = "lon";
          roleNames[Car2goVehicle::DistanceRole] = "distance";
          d->m_vehiclesmodel = new RoleItemModel(roleNames);

and now I want to sort according to distance like this

           d->m_vehiclesmodel->setSortRole(Qt::UserRole);
           d->m_vehiclesmodel->sort(Car2goVehicle::DistanceRole, Qt::AscendingOrder);

But the result is wrong. Can somebody tell me how to sort ?

Thanks.

Answer

Frank Osterfeld picture Frank Osterfeld · Apr 20, 2011

What's wrong with the result? In most cases, one doesn't sort the model itself, but the view, using a QSortFilterProxyModel. Here's the example from the documentation:

QTreeView *treeView = new QTreeView;
MyItemModel *sourceModel = new MyItemModel(this);
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);

proxyModel->setSourceModel(sourceModel);
treeView->setModel(proxyModel);

In your example above, you might mix up roles and columns. Your Role enum should look like this:

enum Role {
    NameRole=Qt::UserRole,
    DistanceRole,
    ...
};

If you want to sort by distance role, you call:

model->setSortRole( Car2goVehicle::DistanceRole );

Then, sort by some column (which has nothing to do with the role), E.g. column 0:

model->sort( 0, Qt::AscendingOrder );