oKcerG / SortFilterProxyModel

A nicely exposed QSortFilterProxyModel for QML
MIT License
298 stars 101 forks source link

[Question] How to add own Sorters? #53

Closed sk2212 closed 4 years ago

sk2212 commented 6 years ago

Hello,

sorry for creating an "issue" here because it is only a question:

I did not find the part of code where the files in "sorters" directory are made available for QML context. So I am not really sure how to add a custom sorter on my own.

The function 'append_sorter' is never called.

Can you please give me a hint?

Thanks!

oKcerG commented 6 years ago

Hello,

The sorters types are exposed to the QML here : https://github.com/oKcerG/SortFilterProxyModel/blob/master/sorters/sortersqmltypes.cpp#L10

So in order to provide a custom Sorter of your own, you need to create a new class inheriting from qqsfpm::Sorter, implement one of these 2 methods : int compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel& proxyModel) const; or bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel& proxyModel) const;

compare when you can, lessThan otherwise. The base compare will call your lessThan. You don't need to take into account the enabled and sortOrder properties in your subclass.

You can of course add additional properties to your class. If you need to invalidate your filter when one of those properties change, just call invalidate() (not the invalidated signal). Note that when the data from the sourceModel changes, your sorter will automatically be called, no need to call invalidate yourself.

When this is done, register your sorter class with qmlRegisterType<YourSorterClass>("YourModule", 1, 0, "YourSorter"); (1, 0 or whatever you want).

Then you can use it like so :

import SortFilterProxyModel 0.2
import YourModule 1.0
// ...
SortFilterProxyModel {
    sourceModel: yourSourceModel
    sorters: YourSorter {
        // ...
    }
}
sk2212 commented 6 years ago

Wow...thank you for detailed information! The main problem was to find 'sortersqmltypes.cpp' where I have to register my own sorter :-).

It is working fine now.

Issue can be closed but it is maybe also relevant for some other users?