I'm trying to find the best possible way to sort a QList of QGraphicsitems by the coord.x() or coord.y() of those items. I have searched a lot during months but couldn't yet find a solution,... it should be something like that,... sorry I'm noob,...I'm trying my best! Thank you! (an idea of how it should be...)
void sortedby()
{
QList<QGraphicsItem *> allitems = items();
QList<QGraphicsItem *> alltypedos;
foreach(auto item, allitems) {
if(item->type() == chord::Type) {
alltypedos.append(item);
}
}
qSort(alltypedos.begin(), alltypedos.end(), item->x());
}
Just use std::sort
with a custom compare function:
bool lessThan(QGraphicsItem * left, QGraphicsItem * right)
{
return (left->x() < right->x());
}
QList<QGraphicsItem *> items;
auto* it1 = new QGraphicsRectItem(QRect(20, 10, 10, 10));
auto* it2 = new QGraphicsRectItem(QRect(20, 10, 10, 10));
auto* it3 = new QGraphicsRectItem(QRect(20, 10, 10, 10));
auto* it4 = new QGraphicsRectItem(QRect(20, 10, 10, 10));
it1->setPos(20, 0);
it2->setPos(10, 0);
it3->setPos(40, 0);
it4->setPos(15, 0);
items << it1 << it2 << it3 << it4;
std::sort(items.begin(), items.end(), lessThan);
for(QGraphicsItem * item: items)
{
qDebug() << item->pos();
}