qt - 在 Qt 中如何对 QModelIndex 的直接子索引进行排序

标签 qt sorting qabstractitemmodel qmodelindex qsortfilterproxymodel

我正在编写一个 C++ 应用程序,它使用 Qt 类来处理某些数据模型。为此,我继承了 QAbstractItemModel:

// the following is a class that represents the actual data used in my application
class EventFragment
{
....
private:
    qint32 address;
    QString memo;
    QDateTime dateCreated;
    QVector<EventFragment*> _children;
....
};

// the following is the model representation that used by my application to display the actual details to the user
class EventModel : public QAbstractItemModel
{
     Q_OBJECT
public:
     explicit EventModel (QObject *parent = 0);
....
private:
     // the following is the root item within the model - I use a tree-like presentation to show my data
     EventFragment* _rootFragment;
};

在某些时候,我的应用程序需要一个排序/过滤选项,所以我还创建了一个继承自 QSortFilterProxyModel

的类
class EventProxyModel : public QSortFilterProxyModel
{
     Q_OBJECT
public:
     explicit EventProxyModel (QObject *parent = 0);
...
public:
     // I had to add my custom implementation in the 'lessThan' method to achieve a
     // more complex sort logic (not just comparing the actual values but using
     // additional conditions to compare the two indexes)
     virtual bool lessThan ( const QModelIndex & left, const QModelIndex & right ) const;
...
};

为了实现排序,我使用了默认的 QSortFilterProxyModel::sort() 方法(我没有在我的代理模型类中重新实现它)并且有一段时间它似乎可以工作。

但在某些时候,我注意到实际的 QSortFilterProxyModel::sort() 方法对整个模型进行排序,而我需要的是仅对某个索引的直接子项进行排序。

我试图重新实现 EventModel 类的 sort() 方法,但过了一会儿我意识到 QSortFilterProxyModel::sort() 根本没有提到它。另一方面,我不确定如何以安全的方式重新排列索引,以便显示模型的 View 不会崩溃。

我认为一定有一种方法可以只对某个QModelIndex 的直接子级进行排序,但我还没有找到。

是否有任何教程/示例可以演示针对我的案例的可能解决方案,或者关于如何解决的一些指南?

问候

最佳答案

如果您想要一个完全不对您不想排序的索引进行比较的优化解决方案,我认为您必须重新实现您自己的 QAbstractProxyModel,这是一项非常重要的任务。但是,如果您不介意未优化的解决方案,我会尝试这样做:

bool EventProxyModel::lessThan( const QModelIndex & left, const QModelIndex & right ) const {
    if ( left.parent() == isTheOneToSortChildrenFor ) {
        ...apply custom comparison
    } else {
        return left.row() < right.row();
    }
}

比较源中的行应该保持除索引之外的所有内容与该特定父项保持原样。

关于qt - 在 Qt 中如何对 QModelIndex 的直接子索引进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724394/

相关文章:

python - Qt QGraphicsDropShadowEffect 没有显示

c++ - 如何从另一个类编辑 QMainWindow UI 小部件?

c++ - 使用gdb/qtdebugger读取Qt应用程序堆栈跟踪时出现问题

c++ - 多个交错 QAbstractItemModel::beginInsertRows()/beginRemoveRows() 后跟一个 endInsertRow()/endRemoveRow() 调用?

qt - 设置交换列的代理模型时自定义分层模型的 View 不正确

c++ - QT Creator 没有自动检测 MSVC2017 64 位编译器

java - 按键升序排序 map

html - list.js javascript 库不工作

vba - VBA 范围自定义排序

c++ - QTreeView:多级列的层次上下文