使用QAbstractItemModel将YAML :: Node转换为树结构

问题描述

Editable Tree Model Example之后,我尝试实现自己的模型,在该模型中我拥有各种YAML::Node,并将它们转换为树状结构以显示QTreeView上。

节点结构

batman:
  type: super hero
  entity: ""
  natural: yes
  attributes:
    powers:
      whip:
        x: ""
        y: ""
      batmobile:
        x: ""
        y: ""

基于节点结构,我做了这样的事情:

void TreeModel::setupModelData(const std::map<std::string,YAML::Node>& schemaMap,TreeItem* parent)
{
    QVector<TreeItem*> parents;
    parents << parent;

    for (const auto& nodeItem : schemaMap)
    {
        rootItem->insertChildren(rootItem->childCount(),1,rootItem->columnCount());
        rootItem->child(rootItem->childCount() - 1)->setData(0,QString::fromStdString(nodeItem.first));
        parents << rootItem->child(rootItem->childCount() - 1);

        nodeIterator(nodeItem.second,parents.last());
    }
}

我遍历包含我的节点(可以是任意数量的节点)的std::map。要遍历每个节点,我在这里

void TreeModel::nodeIterator(const YAML::Node& node,TreeItem* parent)
{
    QVector<TreeItem*> parents;
    parents << parent;

    for (YAML::const_iterator it = node.begin(); it != node.end(); ++it)
    {
        qDebug() << QString::fromStdString(it->first.as<std::string>());
        if (it->second.Type() == YAML::NodeType::Map)
        {
            parents.last()->insertChildren(parent->childCount(),rootItem->columnCount());
            parents.last()->child(parent->childCount() - 1)->setData(0,QString::fromStdString(it->first.as<std::string>()));
            parents << parent->child(parent->childCount() - 1);
            nodeIterator(it->second,parents.last());
        }

        if (it->second.Type() == YAML::NodeType::Scalar)
        {
            qDebug() << QString::fromStdString(it->first.as<std::string>()) << " " << QString::fromStdString(it->second.as<std::string>());
            parents.last()->insertChildren(parent->childCount(),QString::fromStdString(it->first.as<std::string>()));
            parents.last()->child(parent->childCount() - 1)->setData(1,QString::fromStdString(it->second.as<std::string>()));
        }
    }
}

我的结果如下:

enter image description here

我知道我的递归逻辑在某处是错误的。我希望该模型在任何种类的节点上进行迭代,但不确定如何实现此递归行为并随后生成树结构。 目前,我没有MVCE,但希望提供的信息就足够了。

解决方法

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

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

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