gpt4 book ai didi

c++ - 从嵌套的 QStandardItemModel 中的特定列中提取所有数据

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:34 24 4
gpt4 key购买 nike

我有一个 QStandardItemModel,我正在通过 View 将其显示在 QTreeView 中。我的模型包含 2 列,工作方式类似于键和值对。第一列,包含键的修复模板,第二列包含它们对应的值。我的样本树看起来有点像这样:

Item | Attributes
Name Tomato
|-Type Fruit
|-Color Red
Name ...
|-Type ...

正如我所说,第一列中的模板保持不变,但第二列中的值是用户输入的。

我想要什么:

我想(递归地)遍历模型,从 Attributes 列中获取所有值并将其写入文件

到目前为止我做了什么:

void Writer::writeToYaml(const std::shared_ptr<QStandardItemModel>& model, 
const QString& filePath)
{

for(int r = 0; r < model->rowCount(); ++r)
{
QModelIndex index = model->index(r, 1);
QVariant data = model->data(index);
qDebug() << data;

if(model->hasChildren(index))
{
writeToYaml(model, filePath);
}
}
}

当我运行我的代码时,qDebug() 始终只输出 Tomato。我相信循环本身终止于根节点,只产生第一个值。是否可以递归地从嵌套模型中的特定列中提取所有项目?

最佳答案

我是从头开始写的,所以你可能需要稍微调整一下,但它应该可以工作。您需要使用父索引处理较低级别的项目。

但我不确定你的模型是否正确,因为你提供的代码不应该打印'tomato',而是应该创建一个无限循环,因为一旦你递归调用writeToYaml,你就会迭代顶级项目再次。这意味着 model->hasChildren(index) 在您的情况下很可能永远不会正确......

void Writer::writeToYaml(const std::shared_ptr<QAbstractItemModel>& model, const QString& filePath)                 
{

std::stack<QModelIndex> indices;

for (int = model->rowCount() - 1; r >= 0; --r) // iterate from last to first as you put items on a stack
{
indices.push(model->index(r, 1));
}

while (!indices.empty())
{
auto index = indices.top();
indices.pop();

QVariant data = model->data(index);
qDebug() << data;

if (model->hasChildren(index))
{
for (int r = model->rowCount(index) -1 ; r >= 0; --r)
// ^^^^^ note this, this iterates over all children of item on given index
{
indices.push(model->index(r, 1, index));
// ^^^^^ this is the parent index that identifies the item in tree hierarchy
}
}
}
}

关于c++ - 从嵌套的 QStandardItemModel 中的特定列中提取所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com