[Qt-interest] Problem with qSort and QObjects
Florian VICHOT
florian.vichot at diateam.net
Sun Feb 14 16:37:42 CET 2010
Sorry just realised I didn't really answer your second question.
> 1) What I need to do to get the QObject version working? qSort docs
> say that the items need to implement operator<(), but clearly that is
> not enough.
BTW, using QObject by value is a bad idea. I gave the fix to make it
work, but it's not a good idea in most cases. If you copy QObject using
the methods I gave you, it won't copy along signal/slot connections,
etc, since QObject(const QObject& o) is not called.
> 2) Is it possible to overload the operator<() this way (using
> pointers) and use it with qSort?
> bool operator<(const Account * other ) const;
> My app actually stores pointers to objects (extending QObject) in the
> QList that I want to sort, so will it be possible at all?
No you can't do that. What you would need is :
bool operator<(const Account * a, const Account * b ) {...}
but C++ needs at least one class or native type (non-pointers) argument
in an operator overloading prototype. So the prototype above is not valid.
But you can also use the qSort version that takes three arguments:
void qSort ( RandomAccessIterator begin, RandomAccessIterator end,
LessThan lessThan )
and provide your own "lessThan" function to sort. Something like that:
bool my_less_than(const Account * a, const Account * b )
{
return (*a < *b);
}
Use it with qSort(list.begin(), list.end(), &my_less_than); and voilà.
Florian
More information about the Qt-interest-old
mailing list