PDA

View Full Version : Order QList alphabetically



ruben.rodrigues
2nd November 2011, 08:14
Hi all!

I have a qlist of a object that I created. The object contains this fields: GroupID, GroupInfo, Price and Hours.
I need to sort the QList of this Group object by the GroupInfo alphabetic order. Is there a qt function to do this?

Thanks!

ChrisW67
2nd November 2011, 08:33
Assuming you have instance of the objects in the QList, not just pointers, then qSort(), qStableSort() or the STL equivalents. You will need to implement operator<() for the contained class or provide a functor.

ruben.rodrigues
2nd November 2011, 08:36
Assuming you have instance of the objects in the QList, not just pointers, then qSort(), qStableSort() or the STL equivalents. You will need to implement operator<() for the contained class or provide a functor.

thank you for you answer. I have a QList of pointer. Forgot to mention that. Does that mean I can use neither of the function you told me about?

ruben.rodrigues
2nd November 2011, 11:14
Nevermind. I did a funcion to sort the QList by my self. I wish that Qt did that though.

Thanks anyway

d_stranz
3rd November 2011, 22:30
It is easy to sort collections of pointers using STL's sort method. You simply have to implement a comparison function that takes pointer arguments instead of references to object instances. Presumably you already had to do something like this in your own sort function.


I wish that Qt did that though

It does, exactly the way STL's sort does: there are two versions of qSort(), the second of which takes a comparison function as the third argument. So you simply write:



bool myPointerLessThan( MyPointer * p1, MyPointer * p2 )
{
if ( p1 && p2 )
return p1->someValue < p2->someValue;
return false;
}

QList< MyPointer * > myList;
// ... fill the list somehow

qSort( myList.begin(), myList.end(), myPointerLessThan );



Can't get much easier than that.