QProxyModel 将只公开一个子树

问题描述

我需要将树模型的一部分公开为新的树模型。

给定一个这样的树模型:

- a
 |- b
   |- c
- d
 |- e

我想指定一个根元素,例如a 将产生具有以下结构的新模型

- b
 |- c

无需实际复制数据。

因此,我认为代理模型很适合这种情况。我知道在我的 View 类中,我可以根据需要设置 RootIndex。但是我有一个不同的用例,我想使用树的一部分作为 QCompleter 的完成模型。

我从继承 QAbstractProxyModel 开始。

class SubTreeModel : public QAbstractProxyModel
{
    Q_OBJECT
public:
    SubTreeModel(QObject* parent = nullptr);

public:

    QModelIndex RootIndex() const;
    void SetRootIndex(QModelIndex rootIndex);
    QModelIndex mapToSource(const QModelIndex &proxyIndex) const override;
    QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override;
QModelIndex index(int row,int column,const QModelIndex &parent) const override;
    QModelIndex parent(const QModelIndex &child) const override;
    int rowCount(const QModelIndex &parent) const override;
    int columnCount(const QModelIndex &parent) const override;

private:
    QModelIndex m_rootIndex;
};

m_rootIndex 然后应该是源模型的索引,它充当代理模型的根。

在我的理解中,最重要的是让 mapToSourcemapFromSource 正确,然后在剩下的函数中使用它们。但是我面临着困难,这就是我到目前为止所想到的,例如对于mapToSource

QModelIndex SubTreeModel::mapToSource(const QModelIndex& proxyIndex) const
{
    if (not sourceModel() or not m_rootIndex.isValid() or not proxyIndex.isValid())
    {
        return QModelIndex();
    }

    /* accessing the root element of the proxy must be redirected to the correct root element in the
     * whole tree */
    if (not proxyIndex.parent().isValid())
    {
        return sourceModel()->index(proxyIndex.row(),proxyIndex.column(),m_rootIndex);
    }
    return sourceModel()->createIndex(proxyIndex.row(),proxyIndex.parent().internalPointer());
}

最后一个 return 不会编译,因为 createIndex 是受保护的成员。 在执行例如QSortFilterProxyModelQIdentityProxyModel 他们能够通过使用 D 指针技巧调用源模型的 createIndex 函数。我是否需要做同样的事情(这感觉很疯狂!)。有没有另一种方法解决这个问题,哪个更优雅?或者可以不使用createIndex函数来完成吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)