How to apply Filter for Tree which is developed using QStandardItemModel

54 views Asked by At

Implemented Tree using QStandardItemModel.. like below

QStandardItem *americaItem = new QStandardItem("America");
QStandardItem *mexicoItem =  new QStandardItem("Canada");
QStandardItem *usaItem =     new QStandardItem("USA");
QStandardItem *bostonItem =  new QStandardItem("Boston");
QStandardItem *europeItem =  new QStandardItem("Europe");
QStandardItem *italyItem =   new QStandardItem("Italy");
QStandardItem *romeItem =    new QStandardItem("Rome");
QStandardItem *veronaItem =  new QStandardItem("Verona");

//building up the hierarchy
rootNode->    appendRow(americaItem);
rootNode->    appendRow(europeItem);
americaItem-> appendRow(mexicoItem);
americaItem-> appendRow(usaItem);
usaItem->     appendRow(bostonItem);
europeItem->  appendRow(italyItem);
italyItem->   appendRow(romeItem);
italyItem->   appendRow(veronaItem);

//register the model
treeView->setModel(standardModel);

So now Im unable to do search operation, using that QFilterProxyModel im able to search only parent data.. Any suggestion to search parent and child rows too..(using filterAcceptsRow or any other)

1

There are 1 answers

0
Srikanth Reddy On

Implemented search filter like this:

  1. Derived a class from QSortFilterProxyModel
  2. Overrided the filterAcceptsRow method
bool FilterModel::filterAcceptsRow(int source_row,                                       const QModelIndex& source_parent) const
{
    // check the current item

    bool result = QSortFilterProxyModel::filterAcceptsRow(source_row,source_parent);

    QModelIndex currntIndex = sourceModel()->index(source_row, 0, source_parent);

    if (sourceModel()->hasChildren(currntIndex))
    {
        // if it has sub items
        for (int i = 0; i < sourceModel()->rowCount(currntIndex) && !result; ++i)
        {
            // keep the parent if a children is shown
            result = result || filterAcceptsRow(i, currntIndex);
        }
    }
    return result;
}
  1. mFilterProxyModel->setFilterRegExp(ui->mLeSearchFilter->text());