Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
How does QTreeWidgetItem::sortChildren sort?
From the documentation on
http://doc.qt.io/qt-5/qtreewidgetitem.html#sortChildrenit is pretty unclear how the sorting is done.
In my application I'm setting data (
Qt::UserRoleand setting text using specialised formatting that should most definitely not be used for the sorting. I want to achieve sorting by the doubles, but so-far have not been successful to do so. How would I achieve this?
You could create a subclass of QTreeWidgetItem and reimplement the < operator to act on the value you want.
QTreeWidgetItem is pretty oblivious of the underlying data, unless you make your own data sorting I'm not quite sure how (and if) you can do it directly. From what I know the [Tree/List]Widget classes operate on the strings that have the DisplayRole. My suggestion would be to use a QTreeView not QTreeWidget, and provide the data through a model that will support the sorting. Models are pretty flexible and with proxies you can extend them indefinitely. Take a look at this example http://doc.qt.io/qt-5/qtwidgets-itemviews-customsortfiltermodel-example.html where a proxy model is used to provide custom sorting/filtering.
@kshegunov The data I wish to display is already inside a model, specific to our domain - for now it feels like a waste to just duplicate that. But maybe we'll need to go that route at some point anyway.
Nevertheless: very good to know that the class uses the
DisplayRolevalue. I'd kind of expect though that if I call
setTextthat value would be overwritten by my own value - that doesn't seem to be the case. Any chance you know how
setText(which does not accept a
Qt::Role) relates to the
setData(which does accept a
@SGaist Thank you for the suggestion - seems like the obvious idea actually, and this should be rather straightforward.
Recently a colleague needed to do just that (I would even give you source if it weren't proprietary). You could, at some point if you wish, to subclass QAbstractModel and provide implementations without actually duplicating the data. That would sum up to a kind of adapter between Qt's model system and your own data model. Anyways, this is of course if you want and time permits.
On your second question, I believe, but do not hold me to that, since I've not checked it explicitly, setText() just sets the data (probably by means of setData()) for the display role, nothing more.
I have checked in the source code (qt 5.5) and indeed, setText() just invokes setData() with role Qt::DisplayRole.
As a first go I tried the suggestion by @SGaist, which turned out to do exactly what I need for now. We're writing a lot from scratch, so for the future I'll certainly keep the idea of @kshegunov in mind, since it sounds a bit more flexible, so it may be required to support more advanced use cases coming our way in the (near) future.
Thanx to both!