In Qt, how to sort the immediate child indexes of QModelIndex

I am writing a C ++ application that uses Qt classes to work with specific data models. For this, I inherited from 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;
};

At some point, I needed the sort / filter option in my application, so I also created a class that inherits from 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;
...
};

To achieve sorting, I used the QSortFilterProxyModel::sort()default method (I did not override it in my proxy model class) and for some time it worked.

At some point, I noticed that the actual method QSortFilterProxyModel::sort()sorts the entire model, and I need to sort only the immediate children of a specific index.

sort() EventModel, , QSortFilterProxyModel::sort() . , , , , .

, QModelIndex, .

- /, ?

+3
1

, , , , , QAbstractProxyModel, . , , :

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

, , , .

+1

All Articles