Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSortFilterProxyModel: How to display all children?



  • Greetings,
    I have introduced filter using QSortFilterProxyModel in combination with QLineEdit. When I search any keyword then it only displays that child which contains the filtered keyword+ parent.

    Is there any way that it can display all children (which contain filtered keyword+which do not contain) once a keyword matches a tree?

    //------------------------Proxy Model--------------------------
        proxyModel=new QSortFilterProxyModel(this);
        proxyModel->setSourceModel(model);
        proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
        proxyModel->setDynamicSortFilter(true);
        proxyModel->setFilterKeyColumn(-1);
    //--------------------------------------------------------------
    void saved_data::on_lineEdit_textChanged(const QString &arg1)
    {
        proxyModel->setFilterFixedString(arg1);
        proxyModel->setRecursiveFilteringEnabled(true);
        ui->treeView->expandAll();
    }
    


  • @ahsan737
    If I understand right: normally setRecursiveFilteringEnabled() will apply filter to all rows (with the additional "and for any matching child, its parents will be visible as well"), while what you want is "if a row matches, then automatically include all its descendants", right?

    Since I don't see a setting for this, I imagine you must instead implement bool QSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const yourself. You would do your own filter pattern matching for the pattern on nodes. Then you can use source_parent to walk up the tree so as to return true when you find a parent is displayed. This would perhaps assume (depending on how you implement it) that row filtering calls are made in parent-first order, but that is probably the case anyway,



  • @jonb said in QSortFilterProxyModel: How to display all children?:

    while what you want is "if a row matches, then automatically include all its descendants", right?

    Exactly, I want to display all the descendants once any of child has matched.
    Thank you for your detailed reply, I will try to implement it although it sounds a bit complicated to me (as I am a beginner).


Log in to reply