Discussion:
[Interest] efficient natural sorting
Frank Rueter | OHUfx
2018-11-14 02:28:33 UTC
Permalink
Hi,

I need to use the QSortFilterProxyModel to sort strings with numbers in
them, i.e. perform natural sorting.
I found this snippet online:

|import re def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): return [atoi(c) for c in re.split('(\d+)',
text)] l = ['Item1', 'Item2', 'Item3', 'Item10', 'Item20']
l.sort(key=natural_keys) print l |

This works nicely but I’m wondering if it’s reliable and efficient to
implement it like this in the QSortFilterProxyModel.lessThan() method?!

|def lessThan(self, source_left, source_right): natural_keys(source_left)
< natural_keys(source_right) |

Any thoughts on this?

Note: I need to avoid 3rd party libraries.

Cheers,
frank

​
--
ohufxLogo 50x50 <http://www.ohufx.com>
*vfx compositing <http://ohufx.com/compositing.html> | *workflow
customisation and consulting <http://ohufx.com/customising.html>* *
*<http://ohufx.com/compositing.html>*
<http://www.nukepedia.com/nubridge>


Your gateway to over 1,000 free tools... right inside of Nuke
<http://www.nukepedia.com/nubridge>
Shawn Rutledge
2018-11-14 15:14:21 UTC
Permalink
Hi,
I need to use the QSortFilterProxyModel to sort strings with numbers in them, i.e. perform natural sorting.
Another idea is to add a different role to your model, have data() return the original number (int or qreal or whatever) in the variant for that role, and call setSortRole() to tell QSFPM which role to use.
Frank Rueter | OHUfx
2018-11-15 22:37:22 UTC
Permalink
I never have a' Original number" as the strings come from file names and
another app.
QCollator is the ticket.

Cheers,
frank
Post by Shawn Rutledge
Hi,
I need to use the QSortFilterProxyModel to sort strings with numbers in them, i.e. perform natural sorting.
Another idea is to add a different role to your model, have data() return the original number (int or qreal or whatever) in the variant for that role, and call setSortRole() to tell QSFPM which role to use.
_______________________________________________
Interest mailing list
http://lists.qt-project.org/mailman/listinfo/interest
Frank Rueter | OHUfx
2018-11-15 22:36:31 UTC
Permalink
Ha, QCollator is the perfect solution, thank you!
I was not aware of that one.

Cheers,
frank
Hi,
Post by Frank Rueter | OHUfx
This works nicely but I’m wondering if it’s reliable and efficient to
implement it like this in the QSortFilterProxyModel.lessThan() method?!
natural_keys(source_left) < natural_keys(source_right) |
Any thoughts on this?
You can use QCollator to implement natural sorting (by enabling the
numeric mode). Or doesn't it work for your use case?
My 2 c,
_______________________________________________
Interest mailing list
http://lists.qt-project.org/mailman/listinfo/interest
Loading...