简体   繁体   English

QStandardItemModel获取孩子的模型

[英]QStandardItemModel get model of a child

I am a beginner with Qt programming and I have a small problem. 我是Qt编程的初学者,我有一个小问题。 In fact, I have big QStandardItemModel on which I need to find some specific items with keywords. 实际上,我有一个很大的QStandardItemModel ,需要在上面找到一些带有关键字的特定项目。 The idea is to let the user give two inputs, one for the country and another for the city. 这个想法是让用户提供两个输入,一个输入给国家,另一个输入给城市。 Once the country is found,the city has to be searched only under the matching countries. 找到国家/地区后,只需在匹配国家/地区下搜索城市。 But the underlying code, it keep searching on the whole tree model. 但是底层代码会继续搜索整个树模型。

To get the Matching countries, I do: 为了获得匹配国家,我这样做:

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

Then I need to find the city Keyword only inside the matching country: 然后,我只需要在匹配的国家/地区内找到city关键字:

if (!foundCountriesList.isEmpty())
{
    foreach(QStandardItem* item, foundCountriesList)
    {
        foundCitiesList = item->child(0,0)->Model()->findItems(cityKeyword, 
            Qt::MatchStartsWith | Qt::MatchFixedString | 
            Qt::MatchRecursive, 0);
    }
}

But, it keeps searching for the city in the whole TreeModel because whenever I do TreeModel->Item(0,0)->child(0,0)->Model() , I always get TreeModel back. 但是,它一直在整个TreeModel搜索city ,因为每当我执行TreeModel->Item(0,0)->child(0,0)->Model() ,我总会找回TreeModel

Could anyone kindly give me some hints? 有人可以给我一些提示吗?
Thank you in advance! 先感谢您!

I would solve it in the following way: 我将通过以下方式解决它:

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

ie search for the city name and if cities are found, check to which country they belong to. 即搜索城市名称,如果找到城市,请检查它们属于哪个国家。

Since you already loop through all items with desired country, you can filter out the city yourself, by examining items' values. 由于您已经遍历了具有所需国家/地区的所有项目,因此可以通过检查项目的值自己过滤城市。

You can also try using QSortFilterProxyModel . 您也可以尝试使用QSortFilterProxyModel Make one to filter out by country (it's source will be your main model), and another one to filter out by city (it's source will be the proxy model for countries). 制作一个按国家/地区筛选(它的来源将是您的主要模型),另一个按城市(它的来源将成为国家/地区的代理模型)进行筛选。

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

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