Merge branch 'feature/filters-and-sorters'

This commit is contained in:
Pierre-Yves Siret 2017-09-02 18:31:04 +02:00
commit 9009d18554
19 changed files with 2507 additions and 177 deletions

77
.gitignore vendored Normal file
View File

@ -0,0 +1,77 @@
# This file is used to ignore files which are generated
# ----------------------------------------------------------------------------
*~
*.autosave
*.a
*.core
*.moc
*.o
*.obj
*.orig
*.rej
*.so
*.so.*
*_pch.h.cpp
*_resource.rc
*.qm
.#*
*.*#
core
!core/
tags
.DS_Store
.directory
*.debug
Makefile*
*.prl
*.app
moc_*.cpp
ui_*.h
qrc_*.cpp
*.qmlc
Thumbs.db
*.res
*.rc
/.qmake.cache
/.qmake.stash
# qtcreator generated files
*.pro.user*
# qtcreator shadow builds
build-SortFilterProxyModel-*
# xemacs temporary files
*.flc
# Vim temporary files
.*.swp
# Visual Studio generated files
*.ib_pdb_index
*.idb
*.ilk
*.pdb
*.sln
*.suo
*.vcproj
*vcproj.*.*.user
*.ncb
*.sdf
*.opensdf
*.vcxproj
*vcxproj.*
# MinGW generated files
*.Debug
*.Release
# Python byte code
*.pyc
# Binaries
# --------
*.dll
*.exe

101
README.md
View File

@ -8,19 +8,21 @@ Install
##### With [qpm](https://qpm.io) :
1. `qpm install fr.grecko.sortfilterproxymodel`
2. add `include(vendor/vendor.pri)` in your .pro if it is not already done
3. `import SortFilterProxyModel 0.1` to use this library in your QML files
3. `import SortFilterProxyModel 0.2` to use this library in your QML files
##### Without qpm :
1. clone or download this repository
2. add `include (<path/to/SortFilterProxyModel>/SortFilterProxyModel.pri)` in your `.pro`
3. `import SortFilterProxyModel 0.1` to use this library in your QML files
3. `import SortFilterProxyModel 0.2` to use this library in your QML files
Sample Usage
------------
- You can do simple filtering and sorting with SortFilterProxyModel's own properties (`filter*` and `sort*`):
```qml
import QtQuick 2.2
import QtQuick.Controls 1.2
import SortFilterProxyModel 0.1
import SortFilterProxyModel 0.2
ApplicationWindow {
visible: true
@ -32,6 +34,7 @@ ApplicationWindow {
ListElement {
firstName: "Erwan"
lastName: "Castex"
favorite: true
}
// ...
}
@ -43,22 +46,57 @@ ApplicationWindow {
}
SortFilterProxyModel {
id: filteredPersonModel
id: personProxyModel
sourceModel: personModel
filterRoleName: "lastName"
filterPattern: textField.text
filterCaseSensitivity: Qt.CaseInsensitive
sortRoleName: "FirstName"
}
ListView {
anchors { top: textField.bottom; bottom: parent.bottom; left: parent.left; right: parent.right }
model: filteredPersonModel
model: personProxyModel
delegate: Text { text: firstName + " " + lastName}
}
}
```
Here the `ListView` will only show elements that contains the content of the `TextField` in their `lastName` role.
- But you can also achieve more complex filtering or sorting with the `filters` and `sorters` list properties :
```qml
SortFilterProxyModel {
id: personProxyModel
sourceModel: personModel
filters: [
ValueFilter {
enabled: onlyShowFavoritesCheckbox.checked
roleName: "favorite"
value: true
},
AnyOf {
RegExpFilter {
roleName: "lastName"
pattern: textField.text
caseSensitivity: Qt.CaseInsensitive
}
RegExpFilter {
roleName: "firstName"
pattern: textField.text
caseSensitivity: Qt.CaseInsensitive
}
}
]
sorters: [
RoleSorter { roleName: "favorite"; ascendingOrder: false },
RoleSorter { roleName: "firstName" },
RoleSorter { roleName: "lastName" }
]
}
```
This will show in the corresponding `ListView` only the elements where the `firstName` or the `lastName` match the text entered in the `textField`, and if the `onlyShowFavoritesCheckbox` is checked it will aditionnally filter the elements where `favorite` is `true`.
The favorited elements will be shown first and all the elements are sorted by `firstName` and then `lastName`.
License
-------
This library is licensed under the MIT License.
@ -119,56 +157,14 @@ This property only affects the filtering made with `filterPattern`, it does not
By default, the filter is case sensitive.
</li>
<li>
__`filterExpression`__ : _expression_
An expression to implement custom filtering, it must evaluate to a boolean.
It has the same syntax has a [Property Binding](http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html)
except it will be evaluated for each of the source model's rows.
Rows that have their expression evaluating to true will be available in this model.
Data for each row is exposed like for a delegate of a QML View.
The expression has access to the index of the row as the `index` property, and data for each role are accessible under the `model` property.
###### Examples:
Show only even rows:
`filterExpression: index % 2 === 0`
Show all tasks when the corresponding checkbox is checked, otherwise show only unfinished tasks :
```qml
filterExpression: {
if (showDoneTasksCheckBox.checked)
return true;
else
return !model.done;
}
```
This expression is reevaluated for a row every time its model data changes.
When an external property (not `index` or in `model`, like `showDoneTasksCheckBox.checked` here) the expression depends on changes,
the expression is reevaluated for every row of the source model.
To capture the properties the expression depends on, the expression is first executed with invalid data and each property access is detected by the QML engine.
This means that if a property is not accessed because of a conditional, it won't be captured and the expression won't be reevaluted when this property changes. For example with the following expression :
```qml
model.releaseYear > minYearSpinbox.value && model.releaseYear < maxYearSpinbox.value
```
The expression will be correctly reevaluated when the minimum year changes but not when the maximum year changes.
A workaround to this problem is to put the properties the expressions depends on in `var` at the beggining of the expression :
```qml
filterExpression: {
var minimumYear = minYearSpinbox.value;
var maximumYear = maxYearSpinbox.value;
return model.releaseYear > minimumYear && model.releaseYear < maximumYear;
}
```
Note that it is superfluous here for `minimumYear` since it is accessed no matter what.
</li>
<li>
__`sortRoleName`__ : _string_
The role name of the source model's data used for the sorting.
</li>
<li>
__`sortOrder`__ : _enumeration_
The order the source model's data is sorted in. Can be `Qt.AscendingOrder` or `Qt.DescendingOder`.
__`ascendingSortOrder`__ : _bool_
This property holds whether the sort is done in ascending order.
By default, sorting is in ascending order.
</li>
@ -184,13 +180,6 @@ This property holds the local aware setting used for comparing strings when sort
By default, sorting is not local aware.
</li>
<li>
__`sortExpression`__ : _expression_
An expression to implement custom sortering, it must evaluates to a boolean. To read more in depth info about expressions, see `filterExpression`.
Model data is accessible for both row with the `indexLeft`, `modelLeft`, `indexRight` and `modelRight` properties.
The expression should return `true` if the value of the left item is less than the value of the right item, otherwise returns false.
</li>
Contributing
------------
Don't hesitate to open an issue about a suggestion, a bug, a lack of clarity in the documentation, etc.

View File

@ -1,4 +1,10 @@
!contains( CONFIG, c\+\+1[14] ): warning("SortFilterProxyModel needs at least c++11, add CONFIG += c++11 to your .pro")
INCLUDEPATH += $$PWD
HEADERS += $$PWD/qqmlsortfilterproxymodel.h
SOURCES += $$PWD/qqmlsortfilterproxymodel.cpp
HEADERS += $$PWD/qqmlsortfilterproxymodel.h \
$$PWD/filter.h \
$$PWD/sorter.h
SOURCES += $$PWD/qqmlsortfilterproxymodel.cpp \
$$PWD/filter.cpp \
$$PWD/sorter.cpp

748
filter.cpp Normal file
View File

@ -0,0 +1,748 @@
#include "filter.h"
#include <QtQml>
namespace qqsfpm {
/*!
\qmltype Filter
\inqmlmodule SortFilterProxyModel
\brief Base type for the \l SortFilterProxyModel filters
The Filter type cannot be used directly in a QML file.
It exists to provide a set of common properties and methods,
available across all the other filter types that inherit from it.
Attempting to use the Filter type directly will result in an error.
*/
Filter::Filter(QObject *parent) : QObject(parent)
{
}
/*!
\qmlproperty bool Filter::enabled
This property holds whether the filter is enabled.
A disabled filter will accept every rows unconditionally (even if it's inverted).
By default, filters are enabled.
*/
bool Filter::enabled() const
{
return m_enabled;
}
void Filter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
Q_EMIT enabledChanged();
Q_EMIT invalidate();
}
/*!
\qmlproperty bool Filter::inverted
This property holds whether the filter is inverted.
When a filter is inverted, a row normally accepted would be rejected, and vice-versa.
By default, filters are not inverted.
*/
bool Filter::inverted() const
{
return m_inverted;
}
void Filter::setInverted(bool inverted)
{
if (m_inverted == inverted)
return;
m_inverted = inverted;
Q_EMIT invertedChanged();
filterChanged();
}
bool Filter::filterAcceptsRow(const QModelIndex &sourceIndex) const
{
return !m_enabled || filterRow(sourceIndex) ^ m_inverted;
}
QQmlSortFilterProxyModel* Filter::proxyModel() const
{
return m_proxyModel;
}
void Filter::proxyModelCompleted()
{
}
void Filter::filterChanged()
{
if (m_enabled)
invalidate();
}
/*!
\qmltype RoleFilter
\qmlabstract
\inherits Filter
\inqmlmodule SortFilterProxyModel
\brief Base type for filters based on a source model role
The RoleFilter type cannot be used directly in a QML file.
It exists to provide a set of common properties and methods,
available across all the other filter types that inherit from it.
Attempting to use the RoleFilter type directly will result in an error.
*/
/*!
\qmlproperty string RoleFilter::roleName
This property holds the role name that the filter is using to query the source model's data when filtering items.
*/
const QString& RoleFilter::roleName() const
{
return m_roleName;
}
void RoleFilter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
Q_EMIT roleNameChanged();
filterChanged();
}
QVariant RoleFilter::sourceData(const QModelIndex &sourceIndex) const
{
return proxyModel()->sourceData(sourceIndex, m_roleName);
}
/*!
\qmltype ValueFilter
\inherits RoleFilter
\inqmlmodule SortFilterProxyModel
\brief Filters rows matching exactly a value
A ValueFilter is a simple \l RoleFilter that accepts rows matching exactly the filter's value
In the following example, only rows with their \c favorite role set to \c true will be accepted when the checkbox is checked :
\code
CheckBox {
id: showOnlyFavoriteCheckBox
}
SortFilterProxyModel {
sourceModel: contactModel
filters: ValueFilter {
roleName: "favorite"
value: true
enabled: showOnlyFavoriteCheckBox.checked
}
}
\endcode
*/
/*!
\qmlproperty variant ValueFilter::value
This property holds the value used to filter the contents of the source model.
*/
const QVariant &ValueFilter::value() const
{
return m_value;
}
void ValueFilter::setValue(const QVariant& value)
{
if (m_value == value)
return;
m_value = value;
Q_EMIT valueChanged();
filterChanged();
}
bool ValueFilter::filterRow(const QModelIndex& sourceIndex) const
{
return !m_value.isValid() || m_value == sourceData(sourceIndex);
}
/*!
\qmltype IndexFilter
\inherits Filter
\inqmlmodule SortFilterProxyModel
\brief Filters rows based on their source index
An IndexFilter is a filter allowing contents to be filtered based on their source model index.
In the following example, only the first row of the source model will be accepted:
\code
SortFilterProxyModel {
sourceModel: contactModel
filters: IndexFilter {
maximumIndex: 0
}
}
\endcode
*/
/*!
\qmlproperty int IndexFilter::minimumIndex
This property holds the minimumIndex of the filter.
Rows with a source index lower than \c minimumIndex will be rejected.
If \c minimumIndex is negative, it is counted from the end of the source model, meaning that :
\code minimumIndex: -1\endcode
is equivalent to :
\code minimumIndex: sourceModel.count - 1\endcode
By default, no value is set.
*/
const QVariant& IndexFilter::minimumIndex() const
{
return m_minimumIndex;
}
void IndexFilter::setMinimumIndex(const QVariant& minimumIndex)
{
if (m_minimumIndex == minimumIndex)
return;
m_minimumIndex = minimumIndex;
Q_EMIT minimumIndexChanged();
filterChanged();
}
/*!
\qmlproperty int IndexFilter::maximumIndex
This property holds the maximumIndex of the filter.
Rows with a source index higher than \c maximumIndex will be rejected.
If \c maximumIndex is negative, it is counted from the end of the source model, meaning that:
\code maximumIndex: -1\endcode
is equivalent to :
\code maximumIndex: sourceModel.count - 1\endcode
By default, no value is set.
*/
const QVariant& IndexFilter::maximumIndex() const
{
return m_maximumIndex;
}
void IndexFilter::setMaximumIndex(const QVariant& maximumIndex)
{
if (m_maximumIndex == maximumIndex)
return;
m_maximumIndex = maximumIndex;
Q_EMIT maximumIndexChanged();
filterChanged();
}
bool IndexFilter::filterRow(const QModelIndex& sourceIndex) const
{
int sourceRowCount = proxyModel()->sourceModel()->rowCount();
int sourceRow = sourceIndex.row();
bool minimumIsValid;
int minimum = m_minimumIndex.toInt(&minimumIsValid);
int actualMinimum = (sourceRowCount + minimum) % sourceRowCount;
bool lowerThanMinimumIndex = minimumIsValid && sourceRow < actualMinimum;
bool maximumIsValid;
int maximum = m_maximumIndex.toInt(&maximumIsValid);
int actualMaximum = (sourceRowCount + maximum) % sourceRowCount;
bool greaterThanMaximumIndex = maximumIsValid && sourceRow >actualMaximum;
return !lowerThanMinimumIndex && !greaterThanMaximumIndex;
}
/*!
\qmltype RegExpFilter
\inherits RoleFilter
\inqmlmodule SortFilterProxyModel
\brief Filters rows matching a regular expression
A RegExpFilter is a \l RoleFilter that accepts rows matching a regular rexpression.
In the following example, only rows with their \c lastName role beggining with the content of textfield the will be accepted:
\code
TextField {
id: nameTextField
}
SortFilterProxyModel {
sourceModel: contactModel
filters: RegExpFilter {
roleName: "lastName"
pattern: "^" + nameTextField.displayText
}
}
\endcode
*/
/*!
\qmlproperty bool RegExpFilter::pattern
The pattern used to filter the contents of the source model.
\sa syntax
*/
QString RegExpFilter::pattern() const
{
return m_pattern;
}
void RegExpFilter::setPattern(const QString& pattern)
{
if (m_pattern == pattern)
return;
m_pattern = pattern;
m_regExp.setPattern(pattern);
Q_EMIT patternChanged();
filterChanged();
}
/*!
\qmlproperty enum RegExpFilter::syntax
The pattern used to filter the contents of the source model.
Only the source model's value having their \l roleName data matching this \l pattern with the specified \l syntax will be kept.
\value RegExpFilter.RegExp A rich Perl-like pattern matching syntax. This is the default.
\value RegExpFilter.Wildcard This provides a simple pattern matching syntax similar to that used by shells (command interpreters) for "file globbing".
\value RegExpFilter.FixedString The pattern is a fixed string. This is equivalent to using the RegExp pattern on a string in which all metacharacters are escaped.
\value RegExpFilter.RegExp2 Like RegExp, but with greedy quantifiers.
\value RegExpFilter.WildcardUnix This is similar to Wildcard but with the behavior of a Unix shell. The wildcard characters can be escaped with the character "\".
\value RegExpFilter.W3CXmlSchema11 The pattern is a regular expression as defined by the W3C XML Schema 1.1 specification.
\sa pattern
*/
RegExpFilter::PatternSyntax RegExpFilter::syntax() const
{
return m_syntax;
}
void RegExpFilter::setSyntax(RegExpFilter::PatternSyntax syntax)
{
if (m_syntax == syntax)
return;
m_syntax = syntax;
m_regExp.setPatternSyntax(static_cast<QRegExp::PatternSyntax>(syntax));
Q_EMIT syntaxChanged();
filterChanged();
}
/*!
\qmlproperty Qt::CaseSensitivity RegExpFilter::caseSensitivity
This property holds the caseSensitivity of the filter.
*/
Qt::CaseSensitivity RegExpFilter::caseSensitivity() const
{
return m_caseSensitivity;
}
void RegExpFilter::setCaseSensitivity(Qt::CaseSensitivity caseSensitivity)
{
if (m_caseSensitivity == caseSensitivity)
return;
m_caseSensitivity = caseSensitivity;
m_regExp.setCaseSensitivity(caseSensitivity);
Q_EMIT caseSensitivityChanged();
filterChanged();
}
bool RegExpFilter::filterRow(const QModelIndex& sourceIndex) const
{
QString string = sourceData(sourceIndex).toString();
return m_regExp.indexIn(string) != -1;
}
/*!
\qmltype RangeFilter
\inherits RoleFilter
\inqmlmodule SortFilterProxyModel
\brief Filters rows between boundary values
A RangeFilter is a \l RoleFilter that accepts rows if their data is between the filter's minimum and maximum value.
In the following example, only rows with their \c price role set to a value between the tow boundary of the slider will be accepted :
\code
RangeSlider {
id: priceRangeSlider
}
SortFilterProxyModel {
sourceModel: priceModel
filters: RangeFilter {
roleName: "price"
minimumValue: priceRangeSlider.first.value
maximumValue: priceRangeSlider.second.value
}
}
\endcode
*/
/*!
\qmlproperty int RangeFilter::minimumValue
This property holds the minimumValue of the filter.
Rows with a value lower than \c minimumValue will be rejected.
By default, no value is set.
\sa minimumInclusive
*/
QVariant RangeFilter::minimumValue() const
{
return m_minimumValue;
}
void RangeFilter::setMinimumValue(QVariant minimumValue)
{
if (m_minimumValue == minimumValue)
return;
m_minimumValue = minimumValue;
Q_EMIT minimumValueChanged();
filterChanged();
}
/*!
\qmlproperty int RangeFilter::minimumInclusive
This property holds whether the \l minimumValue is inclusive.
By default, the \l minimumValue is inclusive.
\sa minimumValue
*/
bool RangeFilter::minimumInclusive() const
{
return m_minimumInclusive;
}
void RangeFilter::setMinimumInclusive(bool minimumInclusive)
{
if (m_minimumInclusive == minimumInclusive)
return;
m_minimumInclusive = minimumInclusive;
Q_EMIT minimumInclusiveChanged();
filterChanged();
}
/*!
\qmlproperty int RangeFilter::maximumValue
This property holds the maximumValue of the filter.
Rows with a value higher than \c maximumValue will be rejected.
By default, no value is set.
\sa maximumInclusive
*/
QVariant RangeFilter::maximumValue() const
{
return m_maximumValue;
}
void RangeFilter::setMaximumValue(QVariant maximumValue)
{
if (m_maximumValue == maximumValue)
return;
m_maximumValue = maximumValue;
Q_EMIT maximumValueChanged();
filterChanged();
}
/*!
\qmlproperty int RangeFilter::maximumInclusive
This property holds whether the \l minimumValue is inclusive.
By default, the \l minimumValue is inclusive.
\sa minimumValue
*/
bool RangeFilter::maximumInclusive() const
{
return m_maximumInclusive;
}
void RangeFilter::setMaximumInclusive(bool maximumInclusive)
{
if (m_maximumInclusive == maximumInclusive)
return;
m_maximumInclusive = maximumInclusive;
Q_EMIT maximumInclusiveChanged();
filterChanged();
}
bool RangeFilter::filterRow(const QModelIndex& sourceIndex) const
{
QVariant value = sourceData(sourceIndex);
bool lessThanMin = m_minimumValue.isValid() &&
m_minimumInclusive ? value < m_minimumValue : value <= m_minimumValue;
bool moreThanMax = m_maximumValue.isValid() &&
m_maximumInclusive ? value > m_maximumValue : value >= m_maximumValue;
return !(lessThanMin || moreThanMax);
}
/*!
\qmltype ExpressionFilter
\inherits Filter
\inqmlmodule SortFilterProxyModel
\brief Filters row with a custom filtering
An ExpressionFilter is a \l Filter allowing to implement custom filtering based on a javascript expression.
*/
/*!
\qmlproperty expression ExpressionFilter::expression
An expression to implement custom filtering, it must evaluate to a boolean.
It has the same syntax has a \l {http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html} {Property Binding} except it will be evaluated for each of the source model's rows.
Rows that have their expression evaluating to \c true will be accepted by the model.
Data for each row is exposed like for a delegate of a QML View.
This expression is reevaluated for a row every time its model data changes.
When an external property (not \c index or in \c model) the expression depends on changes, the expression is reevaluated for every row of the source model.
To capture the properties the expression depends on, the expression is first executed with invalid data and each property access is detected by the QML engine.
This means that if a property is not accessed because of a conditional, it won't be captured and the expression won't be reevaluted when this property changes.
A workaround to this problem is to access all the properties the expressions depends unconditionally at the beggining of the expression.
*/
const QQmlScriptString& ExpressionFilter::expression() const
{
return m_scriptString;
}
void ExpressionFilter::setExpression(const QQmlScriptString& scriptString)
{
if (m_scriptString == scriptString)
return;
m_scriptString = scriptString;
updateExpression();
Q_EMIT expressionChanged();
filterChanged();
}
bool ExpressionFilter::filterRow(const QModelIndex& sourceIndex) const
{
if (!m_scriptString.isEmpty()) {
QVariantMap modelMap;
QHash<int, QByteArray> roles = proxyModel()->roleNames();
QQmlContext context(qmlContext(this));
auto addToContext = [&] (const QString &name, const QVariant& value) {
context.setContextProperty(name, value);
modelMap.insert(name, value);
};
for (auto it = roles.cbegin(); it != roles.cend(); ++it)
addToContext(it.value(), proxyModel()->sourceData(sourceIndex, it.key()));
addToContext("index", sourceIndex.row());
context.setContextProperty("model", modelMap);
QQmlExpression expression(m_scriptString, &context);
QVariant variantResult = expression.evaluate();
if (expression.hasError()) {
qWarning() << expression.error();
return true;
}
if (variantResult.canConvert<bool>()) {
return variantResult.toBool();
} else {
qWarning("%s:%i:%i : Can't convert result to bool",
expression.sourceFile().toUtf8().data(),
expression.lineNumber(),
expression.columnNumber());
return true;
}
}
return true;
}
void ExpressionFilter::proxyModelCompleted()
{
updateContext();
}
void ExpressionFilter::updateContext()
{
if (!proxyModel())
return;
delete m_context;
m_context = new QQmlContext(qmlContext(this), this);
// what about roles changes ?
QVariantMap modelMap;
auto addToContext = [&] (const QString &name, const QVariant& value) {
m_context->setContextProperty(name, value);
modelMap.insert(name, value);
};
for (const QByteArray& roleName : proxyModel()->roleNames().values())
addToContext(roleName, QVariant());
addToContext("index", -1);
m_context->setContextProperty("model", modelMap);
updateExpression();
}
void ExpressionFilter::updateExpression()
{
if (!m_context)
return;
delete m_expression;
m_expression = new QQmlExpression(m_scriptString, m_context, 0, this);
connect(m_expression, &QQmlExpression::valueChanged, this, &ExpressionFilter::filterChanged);
m_expression->setNotifyOnValueChanged(true);
m_expression->evaluate();
}
QQmlListProperty<Filter> FilterContainer::filters()
{
return QQmlListProperty<Filter>(this, &m_filters,
&FilterContainer::append_filter,
&FilterContainer::count_filter,
&FilterContainer::at_filter,
&FilterContainer::clear_filters);
}
void FilterContainer::append_filter(QQmlListProperty<Filter>* list, Filter* filter)
{
if (!filter)
return;
FilterContainer* that = static_cast<FilterContainer*>(list->object);
that->m_filters.append(filter);
connect(filter, &Filter::invalidate, that, &FilterContainer::filterChanged);
that->filterChanged();
}
int FilterContainer::count_filter(QQmlListProperty<Filter>* list)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->count();
}
Filter* FilterContainer::at_filter(QQmlListProperty<Filter>* list, int index)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->at(index);
}
void FilterContainer::clear_filters(QQmlListProperty<Filter> *list)
{
FilterContainer* that = static_cast<FilterContainer*>(list->object);
that->m_filters.clear();
that->filterChanged();
}
void FilterContainer::proxyModelCompleted()
{
for (Filter* filter : m_filters) {
filter->m_proxyModel = proxyModel();
filter->proxyModelCompleted();
}
}
/*!
\qmltype AnyOf
\inherits Filter
\inqmlmodule SortFilterProxyModel
\brief Filter container accepting rows accepted by at least one of its child filters
The AnyOf type is a \l Filter container that accepts rows if any of its contained (and enabled) filters accept them.
In the following example, only the rows where the \c firstName role or the \c lastName role match the text entered in the \c nameTextField will be accepted :
\code
TextField {
id: nameTextField
}
SortFilterProxyModel {
sourceModel: contactModel
filters: AnyOf {
RegExpFilter {
roleName: "lastName"
pattern: nameTextField.text
caseSensitivity: Qt.CaseInsensitive
}
RegExpFilter {
roleName: "firstName"
pattern: nameTextField.text
caseSensitivity: Qt.CaseInsensitive
}
}
}
\endcode
*/
bool AnyOfFilter::filterRow(const QModelIndex& sourceIndex) const
{
//return true if any of the enabled filters return true
return std::any_of(m_filters.begin(), m_filters.end(),
[&sourceIndex] (Filter* filter) {
return filter->enabled() && filter->filterAcceptsRow(sourceIndex);
}
);
}
/*!
\qmltype AllOf
\inherits Filter
\inqmlmodule SortFilterProxyModel
\brief Filter container accepting rows accepted by all its child filters
The AllOf type is a \l Filter container that accepts rows if all of its contained (and enabled) filters accept them, or if it has no filter.
Using it as a top level filter has the same effect as putting all its child filters as top level filters. It can however be usefull to use an AllOf filter when nested in an AnyOf filter.
*/
bool AllOfFilter::filterRow(const QModelIndex& sourceIndex) const
{
//return true if all filters return false, or if there is no filter.
return std::all_of(m_filters.begin(), m_filters.end(),
[&sourceIndex] (Filter* filter) {
return filter->filterAcceptsRow(sourceIndex);
}
);
}
void registerFilterTypes() {
qmlRegisterUncreatableType<Filter>("SortFilterProxyModel", 0, 2, "Filter", "Filter is an abstract class");
qmlRegisterType<ValueFilter>("SortFilterProxyModel", 0, 2, "ValueFilter");
qmlRegisterType<IndexFilter>("SortFilterProxyModel", 0, 2, "IndexFilter");
qmlRegisterType<RegExpFilter>("SortFilterProxyModel", 0, 2, "RegExpFilter");
qmlRegisterType<RangeFilter>("SortFilterProxyModel", 0, 2, "RangeFilter");
qmlRegisterType<ExpressionFilter>("SortFilterProxyModel", 0, 2, "ExpressionFilter");
qmlRegisterType<AnyOfFilter>("SortFilterProxyModel", 0, 2, "AnyOf");
qmlRegisterType<AllOfFilter>("SortFilterProxyModel", 0, 2, "AllOf");
}
Q_COREAPP_STARTUP_FUNCTION(registerFilterTypes)
}

263
filter.h Normal file
View File

@ -0,0 +1,263 @@
#ifndef FILTER_H
#define FILTER_H
#include <QObject>
#include <QQmlExpression>
#include "qqmlsortfilterproxymodel.h"
namespace qqsfpm {
class Filter : public QObject
{
Q_OBJECT
Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
Q_PROPERTY(bool inverted READ inverted WRITE setInverted NOTIFY invertedChanged)
friend class QQmlSortFilterProxyModel;
friend class FilterContainer;
public:
explicit Filter(QObject *parent = 0);
virtual ~Filter() = default;
bool enabled() const;
void setEnabled(bool enabled);
bool inverted() const;
void setInverted(bool inverted);
bool filterAcceptsRow(const QModelIndex &sourceIndex) const;
Q_SIGNALS:
void enabledChanged();
void invertedChanged();
void invalidate();
protected:
QQmlSortFilterProxyModel* proxyModel() const;
virtual bool filterRow(const QModelIndex &sourceIndex) const = 0;
virtual void proxyModelCompleted();
void filterChanged();
private:
bool m_enabled = true;
bool m_inverted = false;
QQmlSortFilterProxyModel* m_proxyModel = nullptr;
};
class RoleFilter : public Filter
{
Q_OBJECT
Q_PROPERTY(QString roleName READ roleName WRITE setRoleName NOTIFY roleNameChanged)
public:
using Filter::Filter;
const QString& roleName() const;
void setRoleName(const QString& roleName);
Q_SIGNALS:
void roleNameChanged();
protected:
QVariant sourceData(const QModelIndex &sourceIndex) const;
private:
QString m_roleName;
};
class ValueFilter : public RoleFilter {
Q_OBJECT
Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged)
public:
using RoleFilter::RoleFilter;
const QVariant& value() const;
void setValue(const QVariant& value);
protected:
bool filterRow(const QModelIndex &sourceIndex) const override;
Q_SIGNALS:
void valueChanged();
private:
QVariant m_value;
};
class IndexFilter: public Filter {
Q_OBJECT
Q_PROPERTY(QVariant minimumIndex READ minimumIndex WRITE setMinimumIndex NOTIFY minimumIndexChanged)
Q_PROPERTY(QVariant maximumIndex READ maximumIndex WRITE setMaximumIndex NOTIFY maximumIndexChanged)
public:
using Filter::Filter;
const QVariant& minimumIndex() const;
void setMinimumIndex(const QVariant& minimumIndex);
const QVariant& maximumIndex() const;
void setMaximumIndex(const QVariant& maximumIndex);
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
Q_SIGNALS:
void minimumIndexChanged();
void maximumIndexChanged();
private:
QVariant m_minimumIndex;
QVariant m_maximumIndex;
};
class RegExpFilter : public RoleFilter {
Q_OBJECT
Q_PROPERTY(QString pattern READ pattern WRITE setPattern NOTIFY patternChanged)
Q_PROPERTY(PatternSyntax syntax READ syntax WRITE setSyntax NOTIFY syntaxChanged)
Q_PROPERTY(Qt::CaseSensitivity caseSensitivity READ caseSensitivity WRITE setCaseSensitivity NOTIFY caseSensitivityChanged)
public:
enum PatternSyntax {
RegExp = QRegExp::RegExp,
Wildcard = QRegExp::Wildcard,
FixedString = QRegExp::FixedString,
RegExp2 = QRegExp::RegExp2,
WildcardUnix = QRegExp::WildcardUnix,
W3CXmlSchema11 = QRegExp::W3CXmlSchema11 };
Q_ENUMS(PatternSyntax)
using RoleFilter::RoleFilter;
QString pattern() const;
void setPattern(const QString& pattern);
PatternSyntax syntax() const;
void setSyntax(PatternSyntax syntax);
Qt::CaseSensitivity caseSensitivity() const;
void setCaseSensitivity(Qt::CaseSensitivity caseSensitivity);
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
Q_SIGNALS:
void patternChanged();
void syntaxChanged();
void caseSensitivityChanged();
private:
QRegExp m_regExp;
Qt::CaseSensitivity m_caseSensitivity = m_regExp.caseSensitivity();
PatternSyntax m_syntax = static_cast<PatternSyntax>(m_regExp.patternSyntax());
QString m_pattern = m_regExp.pattern();
};
class RangeFilter : public RoleFilter
{
Q_OBJECT
Q_PROPERTY(QVariant minimumValue READ minimumValue WRITE setMinimumValue NOTIFY minimumValueChanged)
Q_PROPERTY(bool minimumInclusive READ minimumInclusive WRITE setMinimumInclusive NOTIFY minimumInclusiveChanged)
Q_PROPERTY(QVariant maximumValue READ maximumValue WRITE setMaximumValue NOTIFY maximumValueChanged)
Q_PROPERTY(bool maximumInclusive READ maximumInclusive WRITE setMaximumInclusive NOTIFY maximumInclusiveChanged)
public:
using RoleFilter::RoleFilter;
QVariant minimumValue() const;
void setMinimumValue(QVariant minimumValue);
bool minimumInclusive() const;
void setMinimumInclusive(bool minimumInclusive);
QVariant maximumValue() const;
void setMaximumValue(QVariant maximumValue);
bool maximumInclusive() const;
void setMaximumInclusive(bool maximumInclusive);
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
Q_SIGNALS:
void minimumValueChanged();
void minimumInclusiveChanged();
void maximumValueChanged();
void maximumInclusiveChanged();
private:
QVariant m_minimumValue;
bool m_minimumInclusive = true;
QVariant m_maximumValue;
bool m_maximumInclusive = true;
};
class ExpressionFilter : public Filter
{
Q_OBJECT
Q_PROPERTY(QQmlScriptString expression READ expression WRITE setExpression NOTIFY expressionChanged)
public:
using Filter::Filter;
const QQmlScriptString& expression() const;
void setExpression(const QQmlScriptString& scriptString);
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
void proxyModelCompleted() override;
Q_SIGNALS:
void expressionChanged();
private:
void updateContext();
void updateExpression();
QQmlScriptString m_scriptString;
QQmlExpression* m_expression = nullptr;
QQmlContext* m_context = nullptr;
};
class FilterContainer : public Filter {
Q_OBJECT
Q_PROPERTY(QQmlListProperty<qqsfpm::Filter> filters READ filters)
Q_CLASSINFO("DefaultProperty", "filters")
public:
using Filter::Filter;
QQmlListProperty<Filter> filters();
static void append_filter(QQmlListProperty<Filter>* list, Filter* filter);
static int count_filter(QQmlListProperty<Filter>* list);
static Filter* at_filter(QQmlListProperty<Filter>* list, int index);
static void clear_filters(QQmlListProperty<Filter>* list);
protected:
void proxyModelCompleted() override;
QList<Filter*> m_filters;
};
class AnyOfFilter : public FilterContainer {
Q_OBJECT
public:
using FilterContainer::FilterContainer;
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
};
class AllOfFilter : public FilterContainer {
Q_OBJECT
public:
using FilterContainer::FilterContainer;
protected:
bool filterRow(const QModelIndex& sourceIndex) const override;
};
}
#endif // FILTER_H

View File

@ -1,10 +1,31 @@
#include "qqmlsortfilterproxymodel.h"
#include <QtQml>
#include <algorithm>
#include "filter.h"
#include "sorter.h"
namespace qqsfpm {
/*!
\page index.html overview
\title SortFilterProxyModel QML Module
SortFilterProxyModel is an implementation of QSortFilterProxyModel conveniently exposed for QML.
\generatelist qmltypesbymodule SortFilterProxyModel
*/
/*!
\qmltype SortFilterProxyModel
\inqmlmodule SortFilterProxyModel
\brief Filters and sorts data coming from a source \l {http://doc.qt.io/qt-5/qabstractitemmodel.html} {QAbstractItemModel}
The SortFilterProxyModel type provides support for filtering and sorting data coming from a source model.
*/
QQmlSortFilterProxyModel::QQmlSortFilterProxyModel(QObject *parent) :
QSortFilterProxyModel(parent),
m_filterExpression(0),
m_compareExpression(0)
QSortFilterProxyModel(parent)
{
connect(this, &QAbstractProxyModel::sourceModelChanged, this, &QQmlSortFilterProxyModel::updateRoles);
connect(this, &QAbstractItemModel::modelReset, this, &QQmlSortFilterProxyModel::updateRoles);
@ -15,6 +36,18 @@ QQmlSortFilterProxyModel::QQmlSortFilterProxyModel(QObject *parent) :
setDynamicSortFilter(true);
}
/*!
\qmlproperty QAbstractItemModel* SortFilterProxyModel::sourceModel
The source model of this proxy model
*/
/*!
\qmlproperty int SortFilterProxyModel::count
The number of rows in the proxy model (not filtered out the source model)
*/
int QQmlSortFilterProxyModel::count() const
{
return rowCount();
@ -32,7 +65,7 @@ void QQmlSortFilterProxyModel::setFilterRoleName(const QString& filterRoleName)
m_filterRoleName = filterRoleName;
updateFilterRole();
emit filterRoleNameChanged();
Q_EMIT filterRoleNameChanged();
}
QString QQmlSortFilterProxyModel::filterPattern() const
@ -48,7 +81,7 @@ void QQmlSortFilterProxyModel::setFilterPattern(const QString& filterPattern)
regExp.setPattern(filterPattern);
QSortFilterProxyModel::setFilterRegExp(regExp);
emit filterPatternChanged();
Q_EMIT filterPatternChanged();
}
QQmlSortFilterProxyModel::PatternSyntax QQmlSortFilterProxyModel::filterPatternSyntax() const
@ -65,7 +98,7 @@ void QQmlSortFilterProxyModel::setFilterPatternSyntax(QQmlSortFilterProxyModel::
regExp.setPatternSyntax(patternSyntaxTmp);
QSortFilterProxyModel::setFilterRegExp(regExp);
emit filterPatternSyntaxChanged();
Q_EMIT filterPatternSyntaxChanged();
}
const QVariant& QQmlSortFilterProxyModel::filterValue() const
@ -80,37 +113,16 @@ void QQmlSortFilterProxyModel::setFilterValue(const QVariant& filterValue)
m_filterValue = filterValue;
invalidateFilter();
emit filterValueChanged();
Q_EMIT filterValueChanged();
}
const QQmlScriptString& QQmlSortFilterProxyModel::filterExpression() const
{
return m_filterScriptString;
}
/*!
\qmlproperty string SortFilterProxyModel::sortRoleName
void QQmlSortFilterProxyModel::setFilterExpression(const QQmlScriptString& filterScriptString)
{
if (m_filterScriptString == filterScriptString)
return;
The role name of the source model's data used for the sorting.
m_filterScriptString = filterScriptString;
QQmlContext* context = new QQmlContext(qmlContext(this));
QVariantMap map;
Q_FOREACH (const QByteArray& roleName, roleNames().values())
map.insert(roleName, QVariant());
context->setContextProperty("model", map);
context->setContextProperty("index", -1);
delete(m_filterExpression);
m_filterExpression = new QQmlExpression(m_filterScriptString, context, 0, this);
connect(m_filterExpression, &QQmlExpression::valueChanged, this, &QQmlSortFilterProxyModel::invalidateFilter);
m_filterExpression->setNotifyOnValueChanged(true);
m_filterExpression->evaluate();
emit filterExpressionChanged();
}
\sa {http://doc.qt.io/qt-5/qsortfilterproxymodel.html#sortRole-prop} {sortRole}, roleForName
*/
const QString& QQmlSortFilterProxyModel::sortRoleName() const
{
@ -124,92 +136,223 @@ void QQmlSortFilterProxyModel::setSortRoleName(const QString& sortRoleName)
m_sortRoleName = sortRoleName;
updateSortRole();
emit sortRoleNameChanged();
Q_EMIT sortRoleNameChanged();
}
void QQmlSortFilterProxyModel::setSortOrder(Qt::SortOrder sortOrder)
bool QQmlSortFilterProxyModel::ascendingSortOrder() const
{
sort(0, sortOrder);
return m_ascendingSortOrder;
}
const QQmlScriptString& QQmlSortFilterProxyModel::sortExpression() const
void QQmlSortFilterProxyModel::setAscendingSortOrder(bool ascendingSortOrder)
{
return m_compareScriptString;
}
void QQmlSortFilterProxyModel::setSortExpression(const QQmlScriptString& compareScriptString)
{
if (m_compareScriptString == compareScriptString)
if (m_ascendingSortOrder == ascendingSortOrder)
return;
m_compareScriptString = compareScriptString;
QQmlContext* context = new QQmlContext(qmlContext(this));
m_ascendingSortOrder = ascendingSortOrder;
Q_EMIT ascendingSortOrderChanged();
invalidate();
}
/*!
\qmlproperty list<Filter> SortFilterProxyModel::filters
This property holds the list of filters for this proxy model. To be included in the model, a row of the source model has to be accepted by all the top level filters of this list.
\sa Filter
*/
QQmlListProperty<Filter> QQmlSortFilterProxyModel::filters()
{
return QQmlListProperty<Filter>(this, &m_filters,
&QQmlSortFilterProxyModel::append_filter,
&QQmlSortFilterProxyModel::count_filter,
&QQmlSortFilterProxyModel::at_filter,
&QQmlSortFilterProxyModel::clear_filters);
}
/*!
\qmlproperty list<Sorter> SortFilterProxyModel::sorters
This property holds the list of sorters for this proxy model. The rows of the source model are sorted by the sorters of this list, in their order of insertion.
\sa Sorter
*/
QQmlListProperty<Sorter> QQmlSortFilterProxyModel::sorters()
{
return QQmlListProperty<Sorter>(this, &m_sorters,
&QQmlSortFilterProxyModel::append_sorter,
&QQmlSortFilterProxyModel::count_sorter,
&QQmlSortFilterProxyModel::at_sorter,
&QQmlSortFilterProxyModel::clear_sorters);
}
void QQmlSortFilterProxyModel::classBegin()
{
}
void QQmlSortFilterProxyModel::componentComplete()
{
m_completed = true;
for (const auto& filter : m_filters)
filter->proxyModelCompleted();
invalidate();
sort(0);
}
QVariant QQmlSortFilterProxyModel::sourceData(const QModelIndex& sourceIndex, const QString& roleName) const
{
int role = sourceModel()->roleNames().key(roleName.toUtf8());
return sourceData(sourceIndex, role);
}
QVariant QQmlSortFilterProxyModel::sourceData(const QModelIndex &sourceIndex, int role) const
{
return sourceModel()->data(sourceIndex, role);
}
/*!
\qmlmethod int SortFilterProxyModel::roleForName(string roleName)
Returns the role number for the given \a roleName.
If no role is found for this \a roleName, \c -1 is returned.
*/
int QQmlSortFilterProxyModel::roleForName(const QString& roleName) const
{
return roleNames().key(roleName.toUtf8(), -1);
}
/*!
\qmlmethod object SortFilterProxyModel::get(int row)
Return the item at \a row in the proxy model as a map of all its roles. This allows the item data to be read (not modified) from JavaScript.
*/
QVariantMap QQmlSortFilterProxyModel::get(int row) const
{
QVariantMap map;
Q_FOREACH (const QByteArray& roleName, roleNames().values())
map.insert(roleName, QVariant());
QModelIndex modelIndex = index(row, 0);
QHash<int, QByteArray> roles = roleNames();
for (QHash<int, QByteArray>::const_iterator it = roles.begin(); it != roles.end(); ++it)
map.insert(it.value(), data(modelIndex, it.key()));
return map;
}
context->setContextProperty("modelLeft", map);
context->setContextProperty("indexLeft", -1);
context->setContextProperty("modelRight", map);
context->setContextProperty("indexRight", -1);
/*!
\qmlmethod variant SortFilterProxyModel::get(int row, string roleName)
delete(m_compareExpression);
m_compareExpression = new QQmlExpression(m_compareScriptString, context, 0, this);
connect(m_compareExpression, &QQmlExpression::valueChanged, this, &QQmlSortFilterProxyModel::invalidate);
m_compareExpression->setNotifyOnValueChanged(true);
m_compareExpression->evaluate();
Return the data for the given \a roleNamte of the item at \a row in the proxy model. This allows the role data to be read (not modified) from JavaScript.
This equivalent to calling \c {data(index(row, 0), roleForName(roleName))}.
*/
QVariant QQmlSortFilterProxyModel::get(int row, const QString& roleName) const
{
return data(index(row, 0), roleForName(roleName));
}
emit sortExpressionChanged();
/*!
\qmlmethod index SortFilterProxyModel::mapToSource(index proxyIndex)
Returns the source model index corresponding to the given \a proxyIndex from the SortFilterProxyModel.
*/
QModelIndex QQmlSortFilterProxyModel::mapToSource(const QModelIndex& proxyIndex) const
{
return QSortFilterProxyModel::mapToSource(proxyIndex);
}
/*!
\qmlmethod int SortFilterProxyModel::mapToSource(int proxyRow)
Returns the source model row corresponding to the given \a proxyRow from the SortFilterProxyModel.
Returns -1 if there is no corresponding row.
*/
int QQmlSortFilterProxyModel::mapToSource(int proxyRow) const
{
QModelIndex proxyIndex = index(proxyRow, 0);
QModelIndex sourceIndex = mapToSource(proxyIndex);
return sourceIndex.isValid() ? sourceIndex.row() : -1;
}
/*!
\qmlmethod QModelIndex SortFilterProxyModel::mapFromSource(QModelIndex sourceIndex)
Returns the model index in the SortFilterProxyModel given the sourceIndex from the source model.
*/
QModelIndex QQmlSortFilterProxyModel::mapFromSource(const QModelIndex& sourceIndex) const
{
return QSortFilterProxyModel::mapFromSource(sourceIndex);
}
/*!
\qmlmethod int SortFilterProxyModel::mapFromSource(int sourceRow)
Returns the row in the SortFilterProxyModel given the \a sourceRow from the source model.
Returns -1 if there is no corresponding row.
*/
int QQmlSortFilterProxyModel::mapFromSource(int sourceRow) const
{
QModelIndex proxyIndex;
if (QAbstractItemModel* source = sourceModel()) {
QModelIndex sourceIndex = source->index(sourceRow, 0);
proxyIndex = mapFromSource(sourceIndex);
}
return proxyIndex.isValid() ? proxyIndex.row() : -1;
}
bool QQmlSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex modelIndex = sourceModel()->index(source_row, 0, source_parent);
bool valueAccepted = !m_filterValue.isValid() || ( m_filterValue == sourceModel()->data(modelIndex, filterRole()) );
if (!m_completed)
return true;
QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent);
bool valueAccepted = !m_filterValue.isValid() || ( m_filterValue == sourceModel()->data(sourceIndex, filterRole()) );
bool baseAcceptsRow = valueAccepted && QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
if (baseAcceptsRow && !m_filterScriptString.isEmpty())
{
QVariantMap map = modelDataMap(modelIndex);
QQmlContext context(qmlContext(this));
context.setContextProperty("model", map);
context.setContextProperty("index", source_row);
QQmlExpression expression(m_filterScriptString, &context, 0);
QVariant result = expression.evaluate();
if (!expression.hasError())
return result.toBool();
else
qWarning() << expression.error();
}
baseAcceptsRow = baseAcceptsRow && std::all_of(m_filters.begin(), m_filters.end(),
[=, &source_parent] (Filter* filter) {
return filter->filterAcceptsRow(sourceIndex);
}
);
return baseAcceptsRow;
}
bool QQmlSortFilterProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
if (!m_compareScriptString.isEmpty())
{
QQmlContext context(qmlContext(this));
context.setContextProperty("modelLeft", modelDataMap(source_left));
context.setContextProperty("indexLeft", source_left.row());
context.setContextProperty("modelRight", modelDataMap(source_right));
context.setContextProperty("indexRight", source_right.row());
QQmlExpression expression(m_compareScriptString, &context, 0);
QVariant result = expression.evaluate();
if (!expression.hasError())
return result.toBool();
else
qWarning() << expression.error();
if (m_completed) {
if (!m_sortRoleName.isEmpty()) {
if (QSortFilterProxyModel::lessThan(source_left, source_right))
return m_ascendingSortOrder;
if (QSortFilterProxyModel::lessThan(source_right, source_left))
return !m_ascendingSortOrder;
}
for(auto sorter : m_sorters) {
if (sorter->enabled()) {
int comparison = sorter->compareRows(source_left, source_right);
if (comparison != 0)
return comparison < 0;
}
}
}
return source_left.row() < source_right.row();
}
void QQmlSortFilterProxyModel::resetInternalData()
{
QSortFilterProxyModel::resetInternalData();
if (sourceModel() && QSortFilterProxyModel::roleNames().isEmpty()) { // workaround for when a model has no roles and roles are added when the model is populated (ListModel)
// QTBUG-57971
connect(sourceModel(), &QAbstractItemModel::rowsInserted, this, &QQmlSortFilterProxyModel::initRoles);
connect(this, &QAbstractItemModel::rowsAboutToBeInserted, this, &QQmlSortFilterProxyModel::initRoles);
}
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
void QQmlSortFilterProxyModel::invalidateFilter()
{
QSortFilterProxyModel::invalidateFilter();
if (m_completed)
QSortFilterProxyModel::invalidateFilter();
}
void QQmlSortFilterProxyModel::invalidate()
{
if (m_completed)
QSortFilterProxyModel::invalidate();
}
void QQmlSortFilterProxyModel::updateFilterRole()
@ -227,7 +370,7 @@ void QQmlSortFilterProxyModel::updateSortRole()
if (!sortRoles.empty())
{
setSortRole(sortRoles.first());
sort(0, sortOrder());
invalidate();
}
}
@ -237,6 +380,14 @@ void QQmlSortFilterProxyModel::updateRoles()
updateSortRole();
}
void QQmlSortFilterProxyModel::initRoles()
{
disconnect(sourceModel(), &QAbstractItemModel::rowsInserted, this, &QQmlSortFilterProxyModel::initRoles);
disconnect(this, &QAbstractItemModel::rowsAboutToBeInserted, this , &QQmlSortFilterProxyModel::initRoles);
resetInternalData();
updateRoles();
}
QVariantMap QQmlSortFilterProxyModel::modelDataMap(const QModelIndex& modelIndex) const
{
QVariantMap map;
@ -246,9 +397,72 @@ QVariantMap QQmlSortFilterProxyModel::modelDataMap(const QModelIndex& modelIndex
return map;
}
void QQmlSortFilterProxyModel::append_filter(QQmlListProperty<Filter>* list, Filter* filter)
{
if (!filter)
return;
QQmlSortFilterProxyModel* that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_filters.append(filter);
connect(filter, &Filter::invalidate, that, &QQmlSortFilterProxyModel::invalidateFilter);
filter->m_proxyModel = that;
that->invalidateFilter();
}
int QQmlSortFilterProxyModel::count_filter(QQmlListProperty<Filter>* list)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->count();
}
Filter* QQmlSortFilterProxyModel::at_filter(QQmlListProperty<Filter>* list, int index)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->at(index);
}
void QQmlSortFilterProxyModel::clear_filters(QQmlListProperty<Filter> *list)
{
QQmlSortFilterProxyModel* that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_filters.clear();
that->invalidateFilter();
}
void QQmlSortFilterProxyModel::append_sorter(QQmlListProperty<Sorter>* list, Sorter* sorter)
{
if (!sorter)
return;
auto that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_sorters.append(sorter);
connect(sorter, &Sorter::invalidate, that, &QQmlSortFilterProxyModel::invalidate);
sorter->m_proxyModel = that;
that->invalidate();
}
int QQmlSortFilterProxyModel::count_sorter(QQmlListProperty<Sorter>* list)
{
auto sorters = static_cast<QList<Sorter*>*>(list->data);
return sorters->count();
}
Sorter* QQmlSortFilterProxyModel::at_sorter(QQmlListProperty<Sorter>* list, int index)
{
auto sorters = static_cast<QList<Sorter*>*>(list->data);
return sorters->at(index);
}
void QQmlSortFilterProxyModel::clear_sorters(QQmlListProperty<Sorter>* list)
{
auto that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_sorters.clear();
that->invalidate();
}
void registerQQmlSortFilterProxyModelTypes() {
qmlRegisterType<QAbstractItemModel>();
qmlRegisterType<QQmlSortFilterProxyModel>("SortFilterProxyModel", 0, 1, "SortFilterProxyModel");
qmlRegisterType<QQmlSortFilterProxyModel>("SortFilterProxyModel", 0, 2, "SortFilterProxyModel");
}
Q_COREAPP_STARTUP_FUNCTION(registerQQmlSortFilterProxyModelTypes)
}

View File

@ -2,21 +2,31 @@
#define QQMLSORTFILTERPROXYMODEL_H
#include <QSortFilterProxyModel>
#include <QQmlExpression>
#include <QQmlParserStatus>
#include <QQmlListProperty>
class QQmlSortFilterProxyModel : public QSortFilterProxyModel
namespace qqsfpm {
class Filter;
class Sorter;
class QQmlSortFilterProxyModel : public QSortFilterProxyModel, public QQmlParserStatus
{
Q_OBJECT
Q_INTERFACES(QQmlParserStatus)
Q_PROPERTY(int count READ count NOTIFY countChanged)
Q_PROPERTY(QString filterRoleName READ filterRoleName WRITE setFilterRoleName NOTIFY filterRoleNameChanged)
Q_PROPERTY(QString filterPattern READ filterPattern WRITE setFilterPattern NOTIFY filterPatternChanged)
Q_PROPERTY(PatternSyntax filterPatternSyntax READ filterPatternSyntax WRITE setFilterPatternSyntax NOTIFY filterPatternSyntaxChanged)
Q_PROPERTY(QVariant filterValue READ filterValue WRITE setFilterValue NOTIFY filterValueChanged)
Q_PROPERTY(QQmlScriptString filterExpression READ filterExpression WRITE setFilterExpression NOTIFY filterExpressionChanged)
Q_PROPERTY(QString sortRoleName READ sortRoleName WRITE setSortRoleName NOTIFY sortRoleNameChanged)
Q_PROPERTY(Qt::SortOrder sortOrder READ sortOrder WRITE setSortOrder)
Q_PROPERTY(QQmlScriptString sortExpression READ sortExpression WRITE setSortExpression NOTIFY sortExpressionChanged)
Q_PROPERTY(bool ascendingSortOrder READ ascendingSortOrder WRITE setAscendingSortOrder NOTIFY ascendingSortOrderChanged)
Q_PROPERTY(QQmlListProperty<qqsfpm::Filter> filters READ filters)
Q_PROPERTY(QQmlListProperty<qqsfpm::Sorter> sorters READ sorters)
public:
enum PatternSyntax {
@ -44,52 +54,79 @@ public:
const QVariant& filterValue() const;
void setFilterValue(const QVariant& filterValue);
const QQmlScriptString& filterExpression() const;
void setFilterExpression(const QQmlScriptString& filterScriptString);
const QString& sortRoleName() const;
void setSortRoleName(const QString& sortRoleName);
void setSortOrder(Qt::SortOrder sortOrder);
bool ascendingSortOrder() const;
void setAscendingSortOrder(bool ascendingSortOrder);
const QQmlScriptString& sortExpression() const;
void setSortExpression(const QQmlScriptString& compareScriptString);
QQmlListProperty<Filter> filters();
QQmlListProperty<Sorter> sorters();
signals:
void classBegin() override;
void componentComplete() override;
QVariant sourceData(const QModelIndex& sourceIndex, const QString& roleName) const;
QVariant sourceData(const QModelIndex& sourceIndex, int role) const;
Q_INVOKABLE int roleForName(const QString& roleName) const;
Q_INVOKABLE QVariantMap get(int row) const;
Q_INVOKABLE QVariant get(int row, const QString& roleName) const;
Q_INVOKABLE QModelIndex mapToSource(const QModelIndex& proxyIndex) const override;
Q_INVOKABLE int mapToSource(int proxyRow) const;
Q_INVOKABLE QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override;
Q_INVOKABLE int mapFromSource(int sourceRow) const;
Q_SIGNALS:
void countChanged();
void filterRoleNameChanged();
void filterPatternSyntaxChanged();
void filterPatternChanged();
void filterValueChanged();
void filterExpressionChanged();
void sortRoleNameChanged();
void sortExpressionChanged();
void ascendingSortOrderChanged();
protected:
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const;
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override;
private slots:
protected Q_SLOTS:
void resetInternalData();
private Q_SLOTS:
void invalidateFilter();
void invalidate();
void updateFilterRole();
void updateSortRole();
void updateRoles();
void initRoles();
private:
QVariantMap modelDataMap(const QModelIndex& modelIndex) const;
static void append_filter(QQmlListProperty<Filter>* list, Filter* filter);
static int count_filter(QQmlListProperty<Filter>* list);
static Filter* at_filter(QQmlListProperty<Filter>* list, int index);
static void clear_filters(QQmlListProperty<Filter>* list);
static void append_sorter(QQmlListProperty<Sorter>* list, Sorter* sorter);
static int count_sorter(QQmlListProperty<Sorter>* list);
static Sorter* at_sorter(QQmlListProperty<Sorter>* list, int index);
static void clear_sorters(QQmlListProperty<Sorter>* list);
QString m_filterRoleName;
QString m_sortRoleName;
QQmlScriptString m_filterScriptString;
QQmlExpression* m_filterExpression;
QQmlScriptString m_compareScriptString;
QQmlExpression* m_compareExpression;
QVariant m_filterValue;
QString m_sortRoleName;
bool m_ascendingSortOrder = true;
QList<Filter*> m_filters;
QList<Sorter*> m_sorters;
bool m_completed = false;
};
#endif // QQMLSORTFILTERPROXYMODEL_H
}
#endif // QQMLSORTFILTERPROXYMODEL_H

306
sorter.cpp Normal file
View File

@ -0,0 +1,306 @@
#include "sorter.h"
#include <QtQml>
namespace qqsfpm {
/*!
\qmltype Sorter
\inqmlmodule SortFilterProxyModel
\brief Base type for the \l SortFilterProxyModel sorters
The Sorter type cannot be used directly in a QML file.
It exists to provide a set of common properties and methods,
available across all the other sorters types that inherit from it.
Attempting to use the Sorter type directly will result in an error.
*/
Sorter::Sorter(QObject *parent) : QObject(parent)
{
}
Sorter::~Sorter() = default;
/*!
\qmlproperty bool Sorter::enabled
This property holds whether the sorter is enabled.
A disabled sorter will not change the order of the rows.
By default, sorters are enabled.
*/
bool Sorter::enabled() const
{
return m_enabled;
}
void Sorter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
Q_EMIT enabledChanged();
Q_EMIT invalidate();
}
bool Sorter::ascendingOrder() const
{
return sortOrder() == Qt::AscendingOrder;
}
void Sorter::setAscendingOrder(bool ascendingOrder)
{
setSortOrder(ascendingOrder ? Qt::AscendingOrder : Qt::DescendingOrder);
}
/*!
\qmlproperty Qt::SortOrder Sorter::sortOrder
This property holds the sort order of this sorter.
\value Qt.AscendingOrder The items are sorted ascending e.g. starts with 'AAA' ends with 'ZZZ' in Latin-1 locales
\value Qt.DescendingOrder The items are sorted descending e.g. starts with 'ZZZ' ends with 'AAA' in Latin-1 locales
By default, sorting is in ascending order.
*/
Qt::SortOrder Sorter::sortOrder() const
{
return m_sortOrder;
}
void Sorter::setSortOrder(Qt::SortOrder sortOrder)
{
if (m_sortOrder == sortOrder)
return;
m_sortOrder = sortOrder;
Q_EMIT sortOrderChanged();
sorterChanged();
}
int Sorter::compareRows(const QModelIndex &source_left, const QModelIndex &source_right) const
{
int comparison = compare(source_left, source_right);
return (m_sortOrder == Qt::AscendingOrder) ? comparison : -comparison;
}
QQmlSortFilterProxyModel* Sorter::proxyModel() const
{
return m_proxyModel;
}
int Sorter::compare(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
if (lessThan(sourceLeft, sourceRight))
return -1;
if (lessThan(sourceRight, sourceLeft))
return 1;
return 0;
}
bool Sorter::lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
Q_UNUSED(sourceLeft)
Q_UNUSED(sourceRight)
return false;
}
void Sorter::proxyModelCompleted()
{
}
void Sorter::sorterChanged()
{
if (m_enabled)
Q_EMIT invalidate();
}
const QString& RoleSorter::roleName() const
{
return m_roleName;
}
/*!
\qmltype RoleSorter
\inherits Sorter
\inqmlmodule SortFilterProxyModel
\brief Sorts rows based on a source model role
A RoleSorter is a simple \l Sorter that sorts rows based on a source model role.
In the following example, rows with be sorted by their \c lastName role :
\code
SortFilterProxyModel {
sourceModel: contactModel
sorters: RoleSorter { roleName: "lastName" }
}
\endcode
*/
/*!
\qmlproperty string RoleSorter::roleName
This property holds the role name that the sorter is using to query the source model's data when sorting items.
*/
void RoleSorter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
Q_EMIT roleNameChanged();
sorterChanged();
}
int RoleSorter::compare(const QModelIndex &sourceLeft, const QModelIndex& sourceRight) const
{
QVariant leftValue = proxyModel()->sourceData(sourceLeft, m_roleName);
QVariant rightValue = proxyModel()->sourceData(sourceRight, m_roleName);
if (leftValue < rightValue)
return -1;
if (leftValue > rightValue)
return 1;
return 0;
}
/*!
\qmltype ExpressionSorter
\inherits Sorter
\inqmlmodule SortFilterProxyModel
\brief Sorts row with a custom sorting
An ExpressionSorter is a \l Sorter allowing to implement custom sorting based on a javascript expression.
*/
/*!
\qmlproperty expression ExpressionSorter::expression
An expression to implement custom sorting, it must evaluate to a bool.
It has the same syntax has a \l {http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html} {Property Binding} except it will be evaluated for each of the source model's rows.
Model data is accessible for both row with the \c indexLeft, \c modelLeft, \c indexRight and \c modelRight properties.
The expression should return \c true if the value of the left item is less than the value of the right item, otherwise returns false.
This expression is reevaluated for a row every time its model data changes.
When an external property (not \c index* or in \c model*) the expression depends on changes, the expression is reevaluated for every row of the source model.
To capture the properties the expression depends on, the expression is first executed with invalid data and each property access is detected by the QML engine.
This means that if a property is not accessed because of a conditional, it won't be captured and the expression won't be reevaluted when this property changes.
A workaround to this problem is to access all the properties the expressions depends unconditionally at the beggining of the expression.
*/
const QQmlScriptString& ExpressionSorter::expression() const
{
return m_scriptString;
}
void ExpressionSorter::setExpression(const QQmlScriptString& scriptString)
{
if (m_scriptString == scriptString)
return;
m_scriptString = scriptString;
updateExpression();
Q_EMIT expressionChanged();
sorterChanged();
}
bool evaluateBoolExpression(QQmlExpression& expression)
{
QVariant variantResult = expression.evaluate();
if (expression.hasError()) {
qWarning() << expression.error();
return false;
}
if (variantResult.canConvert<bool>()) {
return variantResult.toBool();
} else {
qWarning("%s:%i:%i : Can't convert result to bool",
expression.sourceFile().toUtf8().data(),
expression.lineNumber(),
expression.columnNumber());
return false;
}
}
int ExpressionSorter::compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const
{
if (!m_scriptString.isEmpty()) {
QVariantMap modelLeftMap, modelRightMap;
QHash<int, QByteArray> roles = proxyModel()->roleNames();
QQmlContext context(qmlContext(this));
for (auto it = roles.cbegin(); it != roles.cend(); ++it) {
modelLeftMap.insert(it.value(), proxyModel()->sourceData(sourceLeft, it.key()));
modelRightMap.insert(it.value(), proxyModel()->sourceData(sourceRight, it.key()));
}
modelLeftMap.insert("index", sourceLeft.row());
modelRightMap.insert("index", sourceRight.row());
QQmlExpression expression(m_scriptString, &context);
context.setContextProperty("modelLeft", modelLeftMap);
context.setContextProperty("modelRight", modelRightMap);
if (evaluateBoolExpression(expression))
return -1;
context.setContextProperty("modelLeft", modelRightMap);
context.setContextProperty("modelRight", modelLeftMap);
if (evaluateBoolExpression(expression))
return 1;
}
return 0;
}
void ExpressionSorter::proxyModelCompleted()
{
updateContext();
}
void ExpressionSorter::updateContext()
{
if (!proxyModel())
return;
delete m_context;
m_context = new QQmlContext(qmlContext(this), this);
QVariantMap modelLeftMap, modelRightMap;
// what about roles changes ?
for (const QByteArray& roleName : proxyModel()->roleNames().values()) {
modelLeftMap.insert(roleName, QVariant());
modelRightMap.insert(roleName, QVariant());
}
modelLeftMap.insert("index", -1);
modelRightMap.insert("index", -1);
m_context->setContextProperty("modelLeft", modelLeftMap);
m_context->setContextProperty("modelRight", modelRightMap);
updateExpression();
}
void ExpressionSorter::updateExpression()
{
if (!m_context)
return;
delete m_expression;
m_expression = new QQmlExpression(m_scriptString, m_context, 0, this);
connect(m_expression, &QQmlExpression::valueChanged, this, &ExpressionSorter::sorterChanged);
m_expression->setNotifyOnValueChanged(true);
m_expression->evaluate();
}
void registerSorterTypes() {
qmlRegisterUncreatableType<Sorter>("SortFilterProxyModel", 0, 2, "Sorter", "Sorter is an abstract class");
qmlRegisterType<RoleSorter>("SortFilterProxyModel", 0, 2, "RoleSorter");
qmlRegisterType<ExpressionSorter>("SortFilterProxyModel", 0, 2, "ExpressionSorter");
}
Q_COREAPP_STARTUP_FUNCTION(registerSorterTypes)
}

103
sorter.h Normal file
View File

@ -0,0 +1,103 @@
#ifndef SORTER_H
#define SORTER_H
#include <QObject>
#include <QQmlExpression>
#include "qqmlsortfilterproxymodel.h"
namespace qqsfpm {
class Sorter : public QObject
{
Q_OBJECT
Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
Q_PROPERTY(bool ascendingOrder READ ascendingOrder WRITE setAscendingOrder NOTIFY sortOrderChanged)
Q_PROPERTY(Qt::SortOrder sortOrder READ sortOrder WRITE setSortOrder NOTIFY sortOrderChanged)
friend class QQmlSortFilterProxyModel;
public:
Sorter(QObject* parent = nullptr);
virtual ~Sorter() = 0;
bool enabled() const;
void setEnabled(bool enabled);
bool ascendingOrder() const;
void setAscendingOrder(bool ascendingOrder);
Qt::SortOrder sortOrder() const;
void setSortOrder(Qt::SortOrder sortOrder);
int compareRows(const QModelIndex& source_left, const QModelIndex& source_right) const;
Q_SIGNALS:
void enabledChanged();
void sortOrderChanged();
void invalidate();
protected:
QQmlSortFilterProxyModel* proxyModel() const;
virtual int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const;
virtual bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const;
virtual void proxyModelCompleted();
void sorterChanged();
private:
bool m_enabled = true;
Qt::SortOrder m_sortOrder = Qt::AscendingOrder;
QQmlSortFilterProxyModel* m_proxyModel = nullptr;
};
class RoleSorter : public Sorter
{
Q_OBJECT
Q_PROPERTY(QString roleName READ roleName WRITE setRoleName NOTIFY roleNameChanged)
public:
using Sorter::Sorter;
const QString& roleName() const;
void setRoleName(const QString& roleName);
Q_SIGNALS:
void roleNameChanged();
protected:
int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
private:
QString m_roleName;
};
class ExpressionSorter : public Sorter
{
Q_OBJECT
Q_PROPERTY(QQmlScriptString expression READ expression WRITE setExpression NOTIFY expressionChanged)
public:
using Sorter::Sorter;
const QQmlScriptString& expression() const;
void setExpression(const QQmlScriptString& scriptString);
Q_SIGNALS:
void expressionChanged();
protected:
int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
void proxyModelCompleted() override;
private:
void updateContext();
void updateExpression();
QQmlScriptString m_scriptString;
QQmlExpression* m_expression = nullptr;
QQmlContext* m_context = nullptr;
};
}
#endif // SORTER_H

View File

@ -0,0 +1,21 @@
TEMPLATE = app
TARGET = tst_sortfilterproxymodel
QT += qml quick
CONFIG += c++11 warn_on qmltestcase qml_debug no_keywords
include(../SortFilterProxyModel.pri)
HEADERS += \
indexsorter.h
SOURCES += \
tst_sortfilterproxymodel.cpp \
indexsorter.cpp
OTHER_FILES += \
tst_rangefilter.qml \
tst_indexfilter.qml \
tst_sourceroles.qml \
tst_sorters.qml \
tst_helpers.qml \
tst_builtins.qml

19
tests/indexsorter.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "indexsorter.h"
#include <QtQml>
int IndexSorter::compare(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
return sourceLeft.row() - sourceRight.row();
}
int ReverseIndexSorter::compare(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
return sourceRight.row() - sourceLeft.row();
}
void registerIndexSorterTypes() {
qmlRegisterType<IndexSorter>("SortFilterProxyModel.Test", 0, 2, "IndexSorter");
qmlRegisterType<ReverseIndexSorter>("SortFilterProxyModel.Test", 0, 2, "ReverseIndexSorter");
}
Q_COREAPP_STARTUP_FUNCTION(registerIndexSorterTypes)

20
tests/indexsorter.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef INDEXSORTER_H
#define INDEXSORTER_H
#include <sorter.h>
class IndexSorter : public qqsfpm::Sorter
{
public:
using qqsfpm::Sorter::Sorter;
int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
};
class ReverseIndexSorter : public qqsfpm::Sorter
{
public:
using qqsfpm::Sorter::Sorter;
int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
};
#endif // INDEXSORTER_H

54
tests/tst_builtins.qml Normal file
View File

@ -0,0 +1,54 @@
import QtQuick 2.0
import QtQml 2.2
import QtTest 1.1
import SortFilterProxyModel 0.2
Item {
ListModel {
id: testModel
ListElement{role1: 1; role2: 1}
ListElement{role1: 2; role2: 1}
ListElement{role1: 3; role2: 2}
ListElement{role1: 4; role2: 2}
}
ListModel {
id: noRolesFirstTestModel
function initModel() {
noRolesFirstTestModel.append({role1: 1, role2: 1 })
noRolesFirstTestModel.append({role1: 2, role2: 1 })
noRolesFirstTestModel.append({role1: 3, role2: 2 })
noRolesFirstTestModel.append({role1: 4, role2: 2 })
}
}
SortFilterProxyModel {
id: testProxyModel
property string tag: "testProxyModel"
sourceModel: testModel
filterRoleName: "role2"
filterValue: 2
property var expectedData: ([{role1: 3, role2: 2}, {role1: 4, role2: 2}])
}
SortFilterProxyModel {
id: noRolesFirstTestProxyModel
property string tag: "noRolesFirstTestProxyModel"
sourceModel: noRolesFirstTestModel
filterRoleName: "role2"
filterValue: 2
property var expectedData: ([{role1: 3, role2: 2}, {role1: 4, role2: 2}])
}
TestCase {
name: "BuiltinsFilterTests"
function test_filterValue_data() {
return [testProxyModel, noRolesFirstTestProxyModel];
}
function test_filterValue(proxyModel) {
if (proxyModel.sourceModel.initModel)
proxyModel.sourceModel.initModel()
var data = [];
for (var i = 0; i < proxyModel.count; i++)
data.push(proxyModel.get(i));
compare(data, proxyModel.expectedData);
}
}
}

111
tests/tst_helpers.qml Normal file
View File

@ -0,0 +1,111 @@
import QtQuick 2.0
import QtQml 2.2
import QtTest 1.1
import SortFilterProxyModel 0.2
import SortFilterProxyModel.Test 0.2
Item {
ListModel {
id: dataModel
ListElement {
firstName: "Tupac"
lastName: "Shakur"
}
ListElement {
firstName: "Charles"
lastName: "Aznavour"
}
ListElement {
firstName: "Frank"
lastName: "Sinatra"
}
ListElement {
firstName: "Laurent"
lastName: "Garnier"
}
ListElement {
firstName: "Phillipe"
lastName: "Risoli"
}
}
SortFilterProxyModel {
id: testModel
sourceModel: dataModel
}
SortFilterProxyModel {
id: testModel2
sourceModel: dataModel
filters: ValueFilter {
inverted: true
roleName: "lastName"
value: "Sinatra"
}
sorters: [
RoleSorter { roleName: "lastName"},
RoleSorter { roleName: "firstName"}
]
}
TestCase {
name: "Helper functions"
function test_getWithRoleName() {
compare(testModel.get(0, "lastName"), "Shakur");
}
function test_getWithoutRoleName() {
compare(testModel.get(1), { firstName: "Charles", lastName: "Aznavour"});
}
function test_roleForName() {
compare(testModel.data(testModel.index(0, 0), testModel.roleForName("firstName")), "Tupac");
compare(testModel.data(testModel.index(1, 0), testModel.roleForName("lastName")), "Aznavour");
}
function test_mapToSource() {
compare(testModel2.mapToSource(3), 0);
compare(testModel2.mapToSource(4), -1);
}
function test_mapToSourceLoop() {
for (var i = 0; i < testModel2.count; ++i) {
var sourceRow = testModel2.mapToSource(i);
compare(testModel2.get(i).lastName, dataModel.get(sourceRow).lastName);
}
}
function test_mapToSourceLoop_index() {
for (var i = 0; i < testModel2.count; ++i) {
var proxyIndex = testModel2.index(i, 0);
var sourceIndex = testModel2.mapToSource(proxyIndex);
var roleNumber = testModel2.roleForName("lastName");
compare(testModel2.data(proxyIndex, roleNumber), dataModel.data(sourceIndex, roleNumber));
}
}
function test_mapFromSource() {
compare(testModel2.mapFromSource(1), 0);
compare(testModel2.mapFromSource(2), -1);
}
function test_mapFromSourceLoop() {
for (var i = 0; i < dataModel.count; ++i) {
var proxyRow = testModel2.mapFromSource(i);
if (proxyRow !== -1) {
compare(dataModel.get(i).lastName, testModel2.get(proxyRow).lastName);
}
}
}
function test_mapFromSourceLoop_index() {
for (var i = 0; i < dataModel.count; ++i) {
var sourceIndex = dataModel.index(i, 0);
var proxyIndex = testModel2.mapFromSource(sourceIndex);
var roleNumber = testModel2.roleForName("lastName");
if (proxyIndex.valid)
compare(testModel2.data(proxyIndex, roleNumber), dataModel.data(sourceIndex, roleNumber));
}
}
}
}

105
tests/tst_indexfilter.qml Normal file
View File

@ -0,0 +1,105 @@
import QtQuick 2.0
import SortFilterProxyModel 0.2
import QtQml.Models 2.2
import QtTest 1.1
Item {
property list<IndexFilter> filters: [
IndexFilter {
property string tag: "basicUsage"
property int expectedModelCount: 3
property var expectedValues: [3, 1, 2];
minimumIndex: 1; maximumIndex: 3
},
IndexFilter {
property string tag: "outOfBounds"
property int expectedModelCount: 0
minimumIndex: 3; maximumIndex: 1
},
IndexFilter {
property string tag: "0to0Inverted"
property int expectedModelCount: 4
property var expectedValues: [3,1,2,4]
minimumIndex: 0; maximumIndex: 0; inverted: true
},
IndexFilter {
property string tag: "0to0" // bug / issue #15
property int expectedModelCount: 1
property var expectedValues: [5]
minimumIndex: 0; maximumIndex: 0
},
IndexFilter {
property string tag: "basicUsageInverted"
property int expectedModelCount: 2
property var expectedValues: [5,4]
minimumIndex: 1; maximumIndex: 3; inverted: true
},
IndexFilter {
property string tag: "last"
property int expectedModelCount: 1
property var expectedValues: [4]
minimumIndex: -1
},
IndexFilter {
property string tag: "fromEnd"
property int expectedModelCount: 2
property var expectedValues: [2, 4]
minimumIndex: -2
},
IndexFilter {
property string tag: "fromEndRange"
property int expectedModelCount: 2
property var expectedValues: [1, 2]
minimumIndex: -3
maximumIndex: -2
},
IndexFilter {
property string tag: "mixedSignRange"
property int expectedModelCount: 3
property var expectedValues: [3, 1, 2]
minimumIndex: 1
maximumIndex: -2
},
IndexFilter {
property string tag: "noFilter"
property int expectedModelCount: 5
property var expectedValues: [5, 3, 1, 2, 4]
}
]
ListModel {
id: dataModel
ListElement { value: 5 }
ListElement { value: 3 }
ListElement { value: 1 }
ListElement { value: 2 }
ListElement { value: 4 }
}
SortFilterProxyModel {
id: testModel
// FIXME: Crashes/fails with error if I define ListModel directly within sourceModel
sourceModel: dataModel
}
TestCase {
name: "IndexFilterTests"
function test_minMax_data() {
return filters;
}
function test_minMax(filter) {
testModel.filters = filter;
verify(testModel.count === filter.expectedModelCount,
"Expected count " + filter.expectedModelCount + ", actual count: " + testModel.count);
for (var i = 0; i < testModel.count; i++)
{
var modelValue = testModel.data(testModel.index(i, 0));
verify(modelValue === filter.expectedValues[i],
"Expected testModel value " + modelValue + ", actual: " + filter.expectedValues[i]);
}
}
}
}

92
tests/tst_rangefilter.qml Normal file
View File

@ -0,0 +1,92 @@
import QtQuick 2.0
import SortFilterProxyModel 0.2
import QtQml.Models 2.2
import QtTest 1.1
Item {
property list<RangeFilter> filters: [
RangeFilter {
property string tag: "inclusive"
property int expectedModelCount: 3
property var expectedValues: [3, 2, 4]
property QtObject dataModel: dataModel0
roleName: "value"; minimumValue: 2; maximumValue: 4
},
RangeFilter {
property string tag: "explicitInclusive"
property int expectedModelCount: 3
property var expectedValues: [3, 2, 4]
property QtObject dataModel: dataModel0
roleName: "value"; minimumValue: 2; maximumValue: 4; minimumInclusive: true; maximumInclusive: true
},
RangeFilter {
property string tag: "inclusiveMinExclusiveMax"
property int expectedModelCount: 2
property var expectedValues: [2, 3]
property QtObject dataModel: dataModel1
roleName: "value"; minimumValue: 2; maximumValue: 4; minimumInclusive: true; maximumInclusive: false
},
RangeFilter {
property string tag: "exclusiveMinInclusiveMax"
property int expectedModelCount: 2
property var expectedValues: [3, 4]
property QtObject dataModel: dataModel1
roleName: "value"; minimumValue: 2; maximumValue: 4; minimumInclusive: false; maximumInclusive: true
},
RangeFilter {
property string tag: "exclusive"
property int expectedModelCount: 1
property var expectedValues: [3]
property QtObject dataModel: dataModel1
roleName: "value"; minimumValue: 2; maximumValue: 4; minimumInclusive: false; maximumInclusive: false
},
RangeFilter {
property string tag: "outOfBoundsRange"
property int expectedModelCount: 0
property QtObject dataModel: dataModel1
roleName: "value"; minimumValue: 4; maximumValue: 2
}
]
ListModel {
id: dataModel0
ListElement { value: 5 }
ListElement { value: 3 }
ListElement { value: 1 }
ListElement { value: 2 }
ListElement { value: 4 }
}
ListModel {
id: dataModel1
ListElement { value: 5 }
ListElement { value: 2 }
ListElement { value: 3 }
ListElement { value: 1 }
ListElement { value: 4 }
}
SortFilterProxyModel { id: testModel }
TestCase {
name:"RangeFilterTests"
function test_minMax_data() {
return filters;
}
function test_minMax(filter) {
testModel.sourceModel = filter.dataModel;
testModel.filters = filter;
verify(testModel.count === filter.expectedModelCount,
"Expected count " + filter.expectedModelCount + ", actual count: " + testModel.count);
for (var i = 0; i < testModel.count; i++)
{
var modelValue = testModel.data(testModel.index(i, 0), "value");
verify(modelValue === filter.expectedValues[i],
"Expected testModel value " + modelValue + ", actual: " + filter.expectedValues[i]);
}
}
}
}

114
tests/tst_sorters.qml Normal file
View File

@ -0,0 +1,114 @@
import QtQuick 2.0
import QtQml 2.2
import QtTest 1.1
import SortFilterProxyModel 0.2
import SortFilterProxyModel.Test 0.2
Item {
ListModel {
id: listModel
ListElement { test: "first" }
ListElement { test: "second" }
ListElement { test: "third" }
ListElement { test: "fourth" }
}
property list<QtObject> sorters: [
QtObject {
property string tag: "no sorter"
property bool notASorter: true
property var expectedValues: ["first", "second", "third", "fourth"]
},
IndexSorter {
property string tag: "Dummy IndexSorter"
property var expectedValues: ["first", "second", "third", "fourth"]
},
ReverseIndexSorter {
property string tag: "Dummy ReverseIndexSorter"
property var expectedValues: ["fourth", "third", "second", "first"]
},
IndexSorter {
property string tag: "Disabled dummy IndexSorter"
enabled: false
property var expectedValues: ["first", "second", "third", "fourth"]
},
ReverseIndexSorter {
property string tag: "Disabled dummy ReverseIndexSorter"
enabled: false
property var expectedValues: ["first", "second", "third", "fourth"]
},
IndexSorter {
property string tag: "Descending dummy IndexSorter"
ascendingOrder: false
property var expectedValues: ["fourth", "third", "second", "first"]
},
ReverseIndexSorter {
property string tag: "Descending dummy ReverseIndexSorter"
ascendingOrder: false
property var expectedValues: ["first", "second", "third", "fourth"]
},
IndexSorter {
property string tag: "Disabled descending dummy IndexSorter"
enabled: false
ascendingOrder: false
property var expectedValues: ["first", "second", "third", "fourth"]
},
ReverseIndexSorter {
property string tag: "Disabled descending dummy ReverseIndexSorter"
enabled: false
ascendingOrder: false
property var expectedValues: ["first", "second", "third", "fourth"]
}
]
ReverseIndexSorter {
id: reverseIndexSorter
}
SortFilterProxyModel {
id: testModel
sourceModel: listModel
}
TestCase {
name: "SortersTests"
function test_indexOrder_data() {
return sorters;
}
function test_indexOrder(sorter) {
testModel.sorters = sorter;
verifyModelValues(testModel, sorter.expectedValues);
}
function test_enablingSorter() {
reverseIndexSorter.enabled = false;
testModel.sorters = reverseIndexSorter;
var expectedValuesBeforeEnabling = ["first", "second", "third", "fourth"];
var expectedValuesAfterEnabling = ["fourth", "third", "second", "first"];
verifyModelValues(testModel, expectedValuesBeforeEnabling);
reverseIndexSorter.enabled = true;
verifyModelValues(testModel, expectedValuesAfterEnabling);
}
function test_disablingSorter() {
reverseIndexSorter.enabled = true;
testModel.sorters = reverseIndexSorter;
var expectedValuesBeforeDisabling = ["fourth", "third", "second", "first"];
var expectedValuesAfterDisabling = ["first", "second", "third", "fourth"];
verifyModelValues(testModel, expectedValuesBeforeDisabling);
reverseIndexSorter.enabled = false;
verifyModelValues(testModel, expectedValuesAfterDisabling);
}
function verifyModelValues(model, expectedValues) {
verify(model.count === expectedValues.length,
"Expected count " + expectedValues.length + ", actual count: " + model.count);
for (var i = 0; i < model.count; i++)
{
var modelValue = model.data(model.index(i, 0));
verify(modelValue === expectedValues[i],
"Expected testModel value " + expectedValues[i] + ", actual: " + modelValue);
}
}
}
}

View File

@ -0,0 +1,2 @@
#include <QtQuickTest/quicktest.h>
QUICK_TEST_MAIN(SortFilterProxyModel)

49
tests/tst_sourceroles.qml Normal file
View File

@ -0,0 +1,49 @@
import QtQuick 2.0
import QtTest 1.1
import QtQml 2.2
import SortFilterProxyModel 0.2
Item {
ListModel {
id: nonEmptyFirstModel
ListElement {
test: "test"
}
}
SortFilterProxyModel {
id: nonEmptyFirstProxyModel
sourceModel: nonEmptyFirstModel
}
Instantiator {
id: nonEmptyFirstInstantiator
model: nonEmptyFirstProxyModel
QtObject { property var test: model.test }
}
ListModel {
id: emptyFirstModel
}
SortFilterProxyModel {
id: emptyFirstProxyModel
sourceModel: emptyFirstModel
}
Instantiator {
id: emptyFirstInstantiator
model: emptyFirstProxyModel
QtObject { property var test: model.test }
}
TestCase {
name: "RoleTests"
function test_nonEmptyFirst() {
compare(nonEmptyFirstInstantiator.object.test, "test");
}
function test_emptyFirst() {
emptyFirstModel.append({test: "test"});
compare(emptyFirstProxyModel.get(0), {test: "test"});
compare(emptyFirstInstantiator.object.test, "test");
}
}
}