在c ++ Qt中对QStandardItemModel进行排序

时间:2011-04-20 13:25:38

标签: qt sorting model qstandarditemmodel

我有一个QStandardItemModel类型的模型,如下所示:

          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);

现在我想按照这样的距离进行排序

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

但结果是错误的。有人可以告诉我如何排序吗?

感谢。

2 个答案:

答案 0 :(得分:6)

结果出了什么问题? 在大多数情况下,一个不使用QSortFilterProxyModel对模型本身进行排序,而是对视图进行排序。以下是文档中的示例:

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

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

在上面的示例中,您可能会混淆角色和列。您的角色枚举应如下所示:

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

如果您想按距离角色排序,请致电:

model->setSortRole( Car2goVehicle::DistanceRole );

然后,按一些列(与角色无关)排序,例如。第0栏:

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

答案 1 :(得分:0)

如果QSortFilterProxyModel足够强大,我建议不要使用QStandardItemModel::sort()。相反,我坚持使用基本的Qt信号。

在这里,我使用PyQt,但代码也适用于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)

请注意将QHeaderView::sortIndicatorChangedQStandardItemModel::sort相关联的最后一行。