PDA

View Full Version : Sort a QListWidget with Qt::AscendingOrder



ouekah
4th March 2010, 13:30
Hi,

QListWidget::sortItems ( Qt::SortOrder order = Qt::AscendingOrder ) works well, but I don't like the Qt::AscendingOrder policy. Indeed the function first sorts words beginning with an uppercase character and then sorts the other words starting with a lowercase character. Then it concatenates both results together.

For example if you use sortItems on QListWidget containing the following items:

a
India
Abercrombie
iPad
Queen
iPhone
iPod
papa
ISO

You get the following result:

Abercrombie
India
ISO
Queen
a
iPad
iPhone
iPod
papa

...And I would like this result instead:

a
Abercrombie
India
iPad
iPhone
iPod
ISO
papa
Queen

which is an ascending order that ignores cases.

Is there a way to customize the sort policy ?

pitonyak
5th March 2010, 19:26
Disclaimer: I have not tested this...

I believe that you must create your own version of QListWidgetItem and then override operator<.

JuanMO
2nd August 2010, 18:05
Hi All,

I try to do something similar, but I have some issues when trying to overload the operator<
The problem is that I can't recover my original item from the list, I think that I'm wrong in the way I'm extracting it frm the list because I have to use a lots of const_cast, and is suspicious.
Here is the overload code for the operator

struct CustomListWidgetItem : QListWidgetItem
{
CustomListWidgetItem(QListWidget *view =0,int type = Type) : QListWidgetItem(view,type){}
bool operator< ( const QListWidgetItem & other ) const
{
QListWidget * list1 = this->listWidget();
QListWidget * list2 = other.listWidget();

QWidget * w1 = list1->itemWidget(const_cast<CustomListWidgetItem *>(this));
QWidget * w2 = list2->itemWidget(const_cast<QListWidgetItem *>(&other));

Item item1 = (reinterpret_cast<InCallItem*>(w1))->getItem();
Item item2 = (reinterpret_cast<InCallItem*>(w2))->getItem();

return item1 < item2;
}
};

Note:
- list1 == list2 (both items are in the same list)
- w2 == NULL (Why? is correct the way I'm getting w2? should it be of the custom type? perhaps a dynamic_cast?)
- Is there any problem if two items are equivalent? Item1 == Item2 ?


thanks in advence