/ sorters / rolesorter.cpp
rolesorter.cpp
 1  #include "rolesorter.h"
 2  #include "qqmlsortfilterproxymodel.h"
 3  
 4  #include "qvariantlessthan.h"
 5  
 6  namespace qqsfpm {
 7  
 8  /*!
 9      \qmltype RoleSorter
10      \inherits Sorter
11      \inqmlmodule SortFilterProxyModel
12      \ingroup Sorters
13      \brief Sorts rows based on a source model role.
14  
15      A RoleSorter is a simple \l Sorter that sorts rows based on a source model role.
16  
17      In the following example, rows with be sorted by their \c lastName role :
18      \code
19      SortFilterProxyModel {
20         sourceModel: contactModel
21         sorters: RoleSorter { roleName: "lastName" }
22      }
23      \endcode
24  */
25  
26  /*!
27      \qmlproperty string RoleSorter::roleName
28  
29      This property holds the role name that the sorter is using to query the source model's data when sorting items.
30  */
31  const QString& RoleSorter::roleName() const
32  {
33      return m_roleName;
34  }
35  
36  void RoleSorter::setRoleName(const QString& roleName)
37  {
38      if (m_roleName == roleName)
39          return;
40  
41      m_roleName = roleName;
42      Q_EMIT roleNameChanged();
43      invalidate();
44  }
45  
46  QPair<QVariant, QVariant> RoleSorter::sourceData(const QModelIndex &sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel& proxyModel) const
47  {
48      QPair<QVariant, QVariant> pair;
49      int role = proxyModel.roleForName(m_roleName);
50  
51      if (role == -1)
52          return pair;
53  
54      pair.first = proxyModel.sourceData(sourceLeft, role);
55      pair.second = proxyModel.sourceData(sourceRight, role);
56      return pair;
57  }
58  
59  int RoleSorter::compare(const QModelIndex &sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel& proxyModel) const
60  {
61      QPair<QVariant, QVariant> pair = sourceData(sourceLeft, sourceRight, proxyModel);
62      QVariant leftValue = pair.first;
63      QVariant rightValue = pair.second;
64  
65      if (qqsfpm::lessThan(leftValue, rightValue))
66          return -1;
67      if (qqsfpm::lessThan(rightValue, leftValue))
68          return 1;
69  
70      return 0;
71  }
72  
73  }