3

Qtクラスを使用して特定のデータモデルを操作するC++アプリケーションを作成しています。その目的のために私はから継承しました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()メソッドはモデル全体をソートすることに気付きました。必要なのは、特定のインデックスの直接の子のみをソートすることです。

sort()クラスのメソッドを再実装しようとしましたが、しばらくすると、それがまったく参照されていないEventModelことに気付きました。QSortFilterProxyModel::sort()一方、モデルを表示するビューがクラッシュしないように、インデックスを安全な方法で再配置する方法がわかりません。

ある特定の子だけを並べ替える方法があるはずだと思いますが、QModelIndexまだ見つけていません。

私のケースの可能な解決策を示すチュートリアル/例、またはそれを行う方法に関するいくつかのガイドラインはありますか?

よろしく

4

1 に答える 1

3

ソートしたくないインデックスの比較をまったく行わない最適化されたソリューションが必要な場合は、独自の QAbstractProxyModel を再実装する必要があると思いますが、これは重要な作業です。ただし、最適化されていないソリューションで問題ない場合は、次のことを試してください。

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

ソース内の行を比較すると、その特定の親を持つインデックス以外はすべてそのままになります。

于 2012-05-23T20:33:21.953 に答える