繁体   English   中英

QStandardItemModel获取孩子的模型

[英]QStandardItemModel get model of a child

我是Qt编程的初学者,我有一个小问题。 实际上,我有一个很大的QStandardItemModel ,需要在上面找到一些带有关键字的特定项目。 这个想法是让用户提供两个输入,一个输入给国家,另一个输入给城市。 找到国家/地区后,只需在匹配国家/地区下搜索城市。 但是底层代码会继续搜索整个树模型。

为了获得匹配国家,我这样做:

foundCountriesList = TreeModel->findItems(countryKeyword, 
    Qt::MatchStartsWith | Qt::MatchFixedString | Qt::MatchRecursive, 0); 

然后,我只需要在匹配的国家/地区内找到city关键字:

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;
}

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

由于您已经遍历了具有所需国家/地区的所有项目,因此可以通过检查项目的值自己过滤城市。

您也可以尝试使用QSortFilterProxyModel 制作一个按国家/地区筛选(它的来源将是您的主要模型),另一个按城市(它的来源将成为国家/地区的代理模型)进行筛选。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM