Added a QSortFilterProxyModel subclass to enable sorting by different columns in the views.
This commit is contained in:
42
model/generalsortfiltermodel.cpp
Normal file
42
model/generalsortfiltermodel.cpp
Normal file
@ -0,0 +1,42 @@
|
||||
#include "generalsortfiltermodel.h"
|
||||
#include "metadata.h"
|
||||
|
||||
GeneralSortFilterModel::GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel)
|
||||
: QSortFilterProxyModel{sourceModel.get()}
|
||||
, m_sourceModel(sourceModel) {
|
||||
setSourceModel(sourceModel.get());
|
||||
|
||||
m_collator.setNumericMode(true);
|
||||
}
|
||||
|
||||
bool GeneralSortFilterModel::lessThan(const QModelIndex& source_left,
|
||||
const QModelIndex& source_right) const {
|
||||
if (source_left.column() != source_right.column()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QAbstractItemModel* localSourceModel = sourceModel();
|
||||
const int role = GET_ROLE_FOR_COLUMN(source_left.column());
|
||||
const QVariant leftData = localSourceModel->data(source_left);
|
||||
const QVariant rightData = localSourceModel->data(source_right);
|
||||
|
||||
const bool isText = STRING_ROLES.contains(role);
|
||||
if (isText) {
|
||||
const QString leftString = leftData.toString();
|
||||
const QString rightString = rightData.toString();
|
||||
return m_collator.compare(leftString, rightString) > 0;
|
||||
}
|
||||
const bool isInt = INT_ROLES.contains(role);
|
||||
if (isInt) {
|
||||
const int leftInt = leftData.toInt();
|
||||
const int rightInt = rightData.toInt();
|
||||
return leftInt > rightInt;
|
||||
}
|
||||
const bool isDouble = DOUBLE_ROLES.contains(role);
|
||||
if (isDouble) {
|
||||
const int leftInt = leftData.toDouble();
|
||||
const int rightInt = rightData.toDouble();
|
||||
return leftInt > rightInt;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
23
model/generalsortfiltermodel.h
Normal file
23
model/generalsortfiltermodel.h
Normal file
@ -0,0 +1,23 @@
|
||||
#ifndef GENERALSORTFILTERMODEL_H
|
||||
#define GENERALSORTFILTERMODEL_H
|
||||
|
||||
#include <QCollator>
|
||||
#include <QSortFilterProxyModel>
|
||||
|
||||
#include "tablemodel.h"
|
||||
|
||||
class GeneralSortFilterModel : public QSortFilterProxyModel {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel = nullptr);
|
||||
|
||||
/// QSortFilterProxyModel interface
|
||||
protected:
|
||||
bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<TableModel> m_sourceModel;
|
||||
QCollator m_collator; /// for sorting
|
||||
};
|
||||
|
||||
#endif // GENERALSORTFILTERMODEL_H
|
||||
Reference in New Issue
Block a user