简体   繁体   中英

QStandardItemModel get model of a child

I am a beginner with Qt programming and I have a small problem. In fact, I have big QStandardItemModel on which I need to find some specific items with keywords. 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:

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.

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 . 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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