如何按坐标 x 或坐标 y 对 QGraphicsitem 的 QList 进行排序?

How to sort a QList of QGraphicsitem by coord x or coord y?

我正在尝试找到根据这些项目的 coord.x() 或 coord.y() 对 QGraphicsitems 的 QList 进行排序的最佳方法。几个月来我进行了很多搜索,但仍找不到解决方案,...应该是这样的,...对不起,我是菜鸟,...我正在尽力而为!谢谢! (关于它应该如何的想法...)

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());
}

只需将 std::sort 与自定义比较函数一起使用:

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();
    }