Sorting a QListWidget using sortItems()

Kazuma picture Kazuma · Dec 13, 2011 · Viewed 9.2k times · Source

I have issues while using sortItems() on a QListWidget. Here is what happens:

Changes this:

A z d C E o I

to this:

A C I d e o z

But i want it to be:

A C d e I o z

Any way to change to make it sort like that?

Answer

Frank Osterfeld picture Frank Osterfeld · Dec 13, 2011

QListWidget uses the DisplayRole (the item's text) for sorting and calls QString::localeAwareCompare on them. To override the default, you can either change the locale used (see QLocale) or have your own QListWidgetItem subclass reimplementing QListWidgetItem::operator< and let it do the comparison you want.

For anything more advanced, I'd suggest to have a look at QListView, which you could combine either with your own model implementation or the convenience models QStandardItemModel or QStringListModel (the latter could be the most simple and elegant solution in your case). For sorting, you would then put a QSortFilterProxyModel in between the actual model and the view.