PDA

View Full Version : How to qSort a QList of a class



TempleClause
14th October 2012, 21:19
I have a QList of Versions .. where Versions is a class and has two QStrings (text1 and text2)...
how can I sort this QList by text1?

Thanks

ottoshmidt
14th October 2012, 21:52
QStringList::sort () ? Also, qSort from <QtAlgorithms> would be helpful.

Zlatomir
14th October 2012, 21:56
Overload operator<() for Versions class and use qSort (http://doc.qt.digia.com/4.7.1/qtalgorithms.html#qSort) if you have to sort/compare values in multiple places, or use the qSort (http://doc.qt.digia.com/4.7.1/qtalgorithms.html#qSort-2) that takes a lessThan function if you only need the comparison in place for to perform the sort.

TempleClause
14th October 2012, 22:18
thx for the replies!

Can't really get it to work, may someone help me out?



class Version{
public:
Version(QString releaseDate,QString url);
QString releaseDate;
QString URL;
};




QList<Version> allVersions;
// adding some items through xml (irrelevant for this thread)
// how do I sort this list now by the release date?


thanks!

Zlatomir
14th October 2012, 22:45
Have you at least read the links that i gave you in my previous post?


class Version{
public:
Version(QString releaseDate,QString url) : releaseDate(releaseDate), URL(url) { }
QString releaseDate;
QString URL;
};

bool VersionCompare(const Version& i, const Version& j)
{
return i.releaseDate < j.releaseDate; //what ever you consider necessary... for one Version to be lessThan other
}

int main()
{
QList<Version> list;

list.append(Version("zz", "url"));
list.append(Version("gg", "url"));
list.append(Version("aa", "aa"));

qSort(list.begin(), list.end(), VersionCompare);

return 0;
}

TempleClause
14th October 2012, 22:50
of course I did but I didn't get that I have to change the parameters in the compare function :)
It's all clear for me now!
Thanks :D