问题
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.
回答1:
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 );
回答2:
I wouldn't recommend using QSortFilterProxyModel
, if QStandardItemModel::sort()
is powerful enough. Instead, I stick use basic Qt signals.
Here, I'm using PyQt, but the code should also work in C++:
self.model = QStandardItemModel()
self.populate_model()
self.model.setHorizontalHeaderLabels(map(str, range(self.model.rowCount())))
self.treeview.setModel(self.model)
self.treeview.header().setSectionsClickable(True)
self.treeview.header().setSortIndicatorShown(True)
self.treeview.header().sortIndicatorChanged.connect(self.model.sort)
Notice the last line connecting QHeaderView::sortIndicatorChanged
with QStandardItemModel::sort
.
来源:https://stackoverflow.com/questions/5731050/sort-qstandarditemmodel-in-c-qt