ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Is there a way to get a column in a QTreeWidget to sort numerically? I have search the interweb for solutions and have not been able to get anything to work.
Tried converting the data to integer prior to populating the tree and the data would not even populate. Got no errors from this - just empty spaces in the tree.
Here's an example that follows current PyQt best practices. It uses a QStandardItemModel+QtreeView combination, instead of a QTreeWidget. Sorting is done with a QSortFilterProxyModel subclass.
The solution that you found is a tremendously ugly hack that monkey-patches QTreeWidgetItem and overrides its __lt__ method. The __lt__ method is called by the implementation of the comparison operator, "<", and the comparison operator is presumably called by the QTreeWidget's internal sorting routines. And as far as I can tell, its natural_sort_key method (which has the "re" dependency) can be eliminated and replaced with float with the same effect. So:
Hi Dugan,
Your example returned a syntax error on line 47. I am not able to fix it.
With respect to using float instead of the natural_sort_key doesn't work on text. My first column is text and then the next two columns are integers. So column one needs alphbetical sorting and columns two and three need numerical sorting.
I've fixed the example. The syntax error on line 47 is gone, and there is now a sortable left column of text, in addition to two sortable columns of numbers.
And as for the example you found, here's a revision that will work with both text and numbers:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.