filtersorter.cpp
1 #include "filtersorter.h" 2 #include "filters/filter.h" 3 4 namespace qqsfpm { 5 6 /*! 7 \qmltype FilterSorter 8 \inherits Sorter 9 \inqmlmodule SortFilterProxyModel 10 \ingroup Sorters 11 \ingroup FilterContainer 12 \brief Sorts rows based on if they match filters. 13 14 A FilterSorter is a \l Sorter that orders row matching its filters before the rows not matching the filters. 15 16 In the following example, rows with their \c favorite role set to \c true will be ordered at the beginning : 17 \code 18 SortFilterProxyModel { 19 sourceModel: contactModel 20 sorters: FilterSorter { 21 ValueFilter { roleName: "favorite"; value: true } 22 } 23 } 24 \endcode 25 \sa FilterContainer 26 */ 27 28 /*! 29 \qmlproperty list<Filter> FilterSorter::filters 30 \default 31 32 This property holds the list of filters for this filter sorter. 33 If a row match all this FilterSorter's filters, it will be ordered before rows not matching all the filters. 34 35 \sa Filter, FilterContainer 36 */ 37 38 int FilterSorter::compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel &proxyModel) const 39 { 40 bool leftIsAccepted = indexIsAccepted(sourceLeft, proxyModel); 41 bool rightIsAccepted = indexIsAccepted(sourceRight, proxyModel); 42 43 if (leftIsAccepted == rightIsAccepted) 44 return 0; 45 46 return leftIsAccepted ? -1 : 1; 47 } 48 49 void FilterSorter::proxyModelCompleted(const QQmlSortFilterProxyModel& proxyModel) 50 { 51 for (Filter* filter : qAsConst(m_filters)) 52 filter->proxyModelCompleted(proxyModel); 53 } 54 55 void FilterSorter::onFilterAppended(Filter* filter) 56 { 57 connect(filter, &Filter::invalidated, this, &FilterSorter::invalidate); 58 invalidate(); 59 } 60 61 void FilterSorter::onFilterRemoved(Filter* filter) 62 { 63 disconnect(filter, &Filter::invalidated, this, &FilterSorter::invalidate); 64 invalidate(); 65 } 66 67 void FilterSorter::onFiltersCleared() 68 { 69 invalidate(); 70 } 71 72 bool FilterSorter::indexIsAccepted(const QModelIndex& sourceIndex, const QQmlSortFilterProxyModel& proxyModel) const 73 { 74 return std::all_of(m_filters.begin(), m_filters.end(), 75 [&] (Filter* filter) { 76 return filter->filterAcceptsRow(sourceIndex, proxyModel); 77 } 78 ); 79 } 80 81 }