Qt World Summit: Register Today!

[SOLVED]How to reimplement QAbstractItemModel::sort()

  • Hi,

    I got a QTableView and my own model class inherited from QAbstractTableModel. The table is displaying a string in the first column and a checkbox each in column 2 and 3. I want to enable the user to sort the table view by clicking on the header of the the first column. To achieve this I know that I have to implement the sort() function. My question is what do I need to do in the sort() function?

    Do I have to sort the container holding the table items (its currently a QList holding my custom made table items)?
    Or should I rather use a QSortFilterProxyModel? The thing is this is not the final version of the model and item and it is likely that the sorting will get more complex during development.

    Below the header for the model and item classes:

    class MyTableItem
    MyTableItem(const QString& a_Name, bool a_isAlsoTeam, bool a_isAlsoRole);

    const QString& getName();
    void setName(const QString& a_Name);
    bool isTeam();
    void setTeam(bool a_state);
    bool isRole();
    void setRole(bool a_state);

    QString m_strName;
    bool m_bTeam;
    bool m_bRole;

    class MyTableModel : public QAbstractTableModel

    MyTableModel(const QList<MyTableItem*> a_importResults, QObject* parent = 0);

    int rowCount(const QModelIndex& parent = QModelIndex()) const;
    int columnCount(const QModelIndex& parent = QModelIndex()) const;
    QVariant data(const QModelIndex& index, int role) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
    Qt::ItemFlags flags(const QModelIndex& index) const;
    bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
    void sort(int column, Qt::SortOrder order=Qt::AscendingOrder);

    QList<MyTableItem*> m_tableItems;

  • I think I would go for using a QSortFilterProxyModel instead to provide the sorting, and let that one do the work for you.

Log in to reply