QIdentityProxyModel显示空行

时间:2017-06-12 08:56:29

标签: c++ qt

我已经像这样实施了QIdentityProxyModel

class ProxyModel : public QIdentityProxyModel
{
    Q_OBJECT
public:
    ProxyModel(QObject *parent)
    {
        entriesPerPage = 3;
        page = 1;
    }

    inline int getEntriesPerPage() const
    { return entriesPerPage; }
    inline void setEntriesPerPage(int value)
    { entriesPerPage = value; }

    inline qint64 getPage() const
    { return page; }
    inline void setPage(const qint64 &value)
    { page = value; }

    inline int rowCount(const QModelIndex &parent = QModelIndex()) const override{
        Q_UNUSED(parent)
        if(!sourceModel())
            return 0;

        return entriesPerPage * page <= sourceModel()->rowCount()
                ? entriesPerPage
                : sourceModel()->rowCount() - entriesPerPage * (page - 1);
    }

    inline int columnCount(const QModelIndex &parent = QModelIndex()) const override{
        Q_UNUSED(parent);
            return 6;
    }

    QModelIndex ProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
    {
        if(!sourceModel() && !proxyIndex.isValid())
            return QModelIndex();

        return sourceIndex.isValid()
                ? createIndex(sourceIndex.row() % entriesPerPage, sourceIndex.column(), sourceIndex.internalPointer())
                : QModelIndex();
    }

    QModelIndex ProxyModel::mapToSource(const QModelIndex &proxyIndex) const
    {
        if(!sourceModel() && !proxyIndex.isValid())
            return QModelIndex();

        QModelIndex remapped = createIndex(proxyIndex.row() ,
                                           proxyIndex.column(),
                                           proxyIndex.internalPointer());
        return QIdentityProxyModel::mapToSource(remapped);
    }

private:
    int entriesPerPage;
    qint64 page;
};

当我在sourceModel()中插入一行,其索引超过entriesPerPage时,视图显示空行,因此行号大于entriesPerPage,尽管rowCount()返回的数字相等到entriesPerPage

enter image description here

如何摆脱空行?

1 个答案:

答案 0 :(得分:1)

首先。对rowCount覆盖mapFromSource / QIdentityProxyModel是一种不好的做法。我建议您使用QAbstractProxyModel来获得更清晰的代码。

主。您的问题出在getEntriesPerPage / setPage方法中。更新此类数据后,您需要致电beginResetModel / endResetModel

inline void setPage(const qint64 &value)
{
    beginResetModel();
    page = value;
    endResetModel();
}

Offtopic:非常酷,你必须在BSUIR中用Qt编码。谁是你的老师?