Important: Please read the Qt Code of Conduct -

How to filter data in Data Model

  • Hi,
    I have a Data Model which contains all items to be shown by View.
    However i want to have 2 views where one shows only items with for example color "black" and other view shows only items with color "red" (these colors is data of items in data model)

    How to make it? Do I have to create Proxy models in C++ or make somehow filtering in QML side?

  • @Kofr I tried something like this with QStandardItemModel and Quick Controls 2 ComboBox delegate. Not two views, but the idea of hiding in QML is the same. You can hide model items in the delegate based on their state by setting the size to zero and visibility to false. However, the delegate objects still exist so the scroll indicator behaved strangely and keyboard navigation didn't skip the hidden delegate objects but seemed to be lost between the visible objects. As a quick-and-dirty solution it may be acceptable to you depending on the situation. Otherwise a proxy may be the only reliable solution.

  • I have done something similar usinf QSortFilterProxyModel
    basically, you subclass the QSortFilterProxyModel and override the method filterAcceptsRow to return true only when the condition is met.
    And you set the source model for the QSortFilterProxyModel to be your data model then set the view's model to be the proxy model.

  • I have created an example which shows how to use QSortFilterProxyModel along with QAbstractListModel.

    Pleasse find the blog post
    and Source code.

    Hope this helps. Happy Coding!!

  • @Mammamia thx
    I have very large QAbstratItemModel and having two FilterModels is expensive I suppose as QSortFilterProxyModel rescan source model each time it changes data.
    I am still thinking about that.

Log in to reply