Advertisement
VRonin

Sort Multiple Columns Proxy

May 11th, 2017
764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // multisort.h
  2. #include <QSortFilterProxyModel>
  3. #include <QList>
  4. #include <QPair>
  5. class MultySortProxy : public QSortFilterProxyModel
  6. {
  7.     Q_OBJECT
  8.     Q_DISABLE_COPY(MultySortProxy)
  9. public:
  10.     explicit MultySortProxy(QObject *parent = nullptr);
  11.     virtual ~MultySortProxy();
  12.     void addSortPriority(int col, int role = Qt::DisplayRole);
  13.     void revoveSortPriority(int col, int role = Qt::DisplayRole);
  14.     void clearSortPriority();
  15.     void insertSortPriority(int level, int col, int role = Qt::DisplayRole);
  16. protected:
  17.     virtual bool lessThan(const QModelIndex & source_left, const QModelIndex & source_right) const override;
  18. protected:
  19.     QList<QPair<int, int>> m_sortPriority;
  20. };
  21. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  22. // multisort.cpp
  23. #include "multisort.h"
  24. #include <QVariant>
  25. MultySortProxy::MultySortProxy(QObject *parent)
  26.     : QSortFilterProxyModel(parent)
  27. {}
  28.  
  29. MultySortProxy::~MultySortProxy(){}
  30.  
  31. void MultySortProxy::addSortPriority(int col, int role)
  32. {
  33.     m_sortPriority.append(QPair<int, int>(col, role));
  34. }
  35.  
  36. void MultySortProxy::revoveSortPriority(int col, int role)
  37. {
  38.     m_sortPriority.removeAt(m_sortPriority.indexOf(QPair<int, int>(col, role)));
  39. }
  40.  
  41. void MultySortProxy::clearSortPriority()
  42. {
  43.     m_sortPriority.clear();
  44. }
  45.  
  46. void MultySortProxy::insertSortPriority(int level, int col, int role)
  47. {
  48.     m_sortPriority.insert(level, QPair<int, int>(col, role));
  49. }
  50.  
  51. bool MultySortProxy::lessThan(const QModelIndex & source_left, const QModelIndex & source_right) const
  52. {
  53.     for (auto i = m_sortPriority.constBegin(); i != m_sortPriority.constEnd();++i){
  54.         const QVariant leftData = source_left.model()->index(source_left.row(), i->first, source_left.parent()).data(i->second);
  55.         const QVariant rightData = source_right.model()->index(source_right.row(), i->first, source_right.parent()).data(i->second);
  56.         if (leftData < rightData)
  57.             return true;
  58.         if (rightData < leftData)
  59.             return false;
  60.     }
  61.     return false;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement