C++ QStandardItemModel获取孩子的模型

C++ QStandardItemModel获取孩子的模型,c++,qt,qstandarditemmodel,C++,Qt,Qstandarditemmodel,我是Qt编程的初学者,我有一个小问题。 事实上,我有一个大的QStandardItemModel,我需要在上面找到一些带有关键字的特定项目。这样做的目的是让用户提供两种输入,一种用于国家,另一种用于城市。一旦找到国家,城市只需在匹配的国家下搜索。但是底层代码,它一直在搜索整个树模型 要获得匹配的国家,我需要: foundCountriesList = TreeModel->findItems(countryKeyword, Qt::MatchStartsWith | Qt::Ma

我是Qt编程的初学者,我有一个小问题。 事实上,我有一个大的
QStandardItemModel
,我需要在上面找到一些带有关键字的特定项目。这样做的目的是让用户提供两种输入,一种用于国家,另一种用于城市。一旦找到国家,城市只需在匹配的国家下搜索。但是底层代码,它一直在搜索整个树模型

要获得匹配的国家,我需要:

foundCountriesList = TreeModel->findItems(countryKeyword, 
    Qt::MatchStartsWith | Qt::MatchFixedString | Qt::MatchRecursive, 0); 
然后我只需要在匹配的国家/地区内找到
城市
关键字:

if (!foundCountriesList.isEmpty())
{
    foreach(QStandardItem* item, foundCountriesList)
    {
        foundCitiesList = item->child(0,0)->Model()->findItems(cityKeyword, 
            Qt::MatchStartsWith | Qt::MatchFixedString | 
            Qt::MatchRecursive, 0);
    }
}
但是,它一直在整个
TreeModel
中搜索
city
,因为每当我执行
TreeModel->Item(0,0)->child(0,0)->Model()
,我总是会返回
TreeModel

谁能给我一些提示吗?

提前谢谢你

由于您已经循环浏览了所有具有所需国家/地区的项目,因此您可以通过检查项目的值自己筛选出城市


您也可以尝试使用。制作一个按国家过滤(其来源将是您的主要模型),另一个按城市过滤(其来源将是国家的代理模型)

我将用以下方法解决它:

QStandardItem *findCityItem(const QString &city, const QString &country)
{
  auto cityItems = TreeModel->findItems(city,
                                        Qt::MatchRecursive | Qt::MatchWrap | Qt::MatchExactly, 0);
  for (auto cityItem : cityItems)
  {
    auto parent = item->parent();
    if (parent && (parent->data().toString() == country))
    {
      return item;
    }
  }
  return nullptr;
}

i、 e.搜索城市名称,如果找到城市,请检查它们属于哪个国家。

您的树结构是什么?城市项目是相应国家/地区项目的子项目吗?您有一个模型,这就是为什么
model()
总是返回相同的模型。顺便说一句,如果(!foundCountriesList.isEmpty())
是不必要的
item->child(0,0)->model()->
TreeModel->
@Dimitry Sazonov:好的,但是有什么方法可以从这个独特的大模型中构建或提取子模型吗?@AndySankarley您应该子类化并重新实现方法。或者只是从所需的项目创建一个新模型。手动操作,无任何
findItems
calls@vahancho:是的,事实上,每个国家/地区节点都包含城市节点等。谢谢,这可能会奏效,但实际上TreeModel是一个非常大的对象,包含很多子节点和子节点的子节点。对一个城市进行这样的研究需要花费很多时间,这就是为什么我需要他只在特定的国家下搜索。我明白了,但要在特定的国家下搜索,你需要先找到那个国家。要找到国家,我刚刚做了:foundCountriesList=TreeModel->findItems(countryKeyword,Qt::MatchStartsWith | Qt::MatchFixedString,0);这非常有效。