QStandardItemModel 获取子模型

QStandardItemModel get model of a child

本文关键字:模型 获取 QStandardItemModel      更新时间:2023-10-16

我是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。制作一个按国家/地区过滤掉(它的源将是你的主模型(,另一个按城市过滤掉(它的源将是国家/地区的代理模型(。