QT:TreeView刷新后记忆展开,可多层嵌套

逻辑结构

界面上有一个”刷新“,点击后刷新列表,并按刷新前的情况展开。


具体代码

我的treeview是ui提升来的,_treeViewModel是treeview对应的model。

.h

typedef struct _NodeP
{
    int nRowNo;
    std::vector<_NodeP> arChildren;
}NodeExpand;

class A: public QWidget
{
Q_OBJECT

public:
    void init();
    void startRemeberNode();
    void startExpandNode();
    void recursiveRememberNodeState(NodeExpand& ne, QModelIndex root);
    void recursiveExpandNode(NodeExpand& ne, QModelIndex root);
private:
    Ui::A*ui;
    NodeExpand _nodeExpand;
    QStandardItemModel *_treeViewModel = Q_NULLPTR;
};

#endif

 ”刷新“按钮调用 init(),因为存在多次刷新,所以每一次startRemeberNode的时候要清空arChildren。

/.cpp

void A::init()
{
    startRemeberNode();

    /**
    * 这里写你的刷新函数
    **/

    startExpandNode();
}

void A::recursiveRememberNodeState(NodeExpand &ne, QModelIndex root)
{
    int nChild = _treeViewModel->rowCount(root);

    for (int i = 0; i < nChild; i++)
    {
        QModelIndex index = _treeViewModel->index(i, 0, root);
        if (ui->treeView->isExpanded(index))
        {
            NodeExpand n;
            n.nRowNo = i;
            recursiveRememberNodeState(n, index);
            ne.arChildren.push_back(n);
        }
    }
}


void A::recursiveExpandNode(NodeExpand &ne, QModelIndex root)
{
    QModelIndex index = _treeViewModel->index(ne.nRowNo, 0, root);
    if (!index.isValid())
    {
        return;
    }


    ui->treeView->expand(index);
    for (int i = 0; i < ne.arChildren.size(); i++)
    {
        recursiveExpandNode(ne.arChildren[i], index);
    }
}

void A::startExpandNode()
{
    QModelIndex root = ui->treeView->rootIndex();
    for (int i = 0; i < _nodeExpand.arChildren.size(); i++)
    {
        recursiveExpandNode(_nodeExpand.arChildren[i], root);
    }
}


void A::startRemeberNode()
{
    _nodeExpand.arChildren.clear();
    QModelIndex root = ui->treeView->rootIndex();
    recursiveRememberNodeState(_nodeExpand, root);
}

参考借鉴

QTreeVIew 记忆展开状态, 在数据更新时能保持原样_qtreeview model展开状态记录-CSDN博客

你可能感兴趣的:(qt,开发语言)