根据中心点从最小到最大对QGraphicsItems QList进行排序

Sort QGraphicsItems QList based on center point min to max

本文关键字:QList QGraphicsItems 排序 中心点      更新时间:2023-10-16

如何根据QGraphicsItems的边界Rect中心点对其列表进行排序?我希望列表从最小Y值到最大Y值进行排序。

感谢

QList<QGraphicsItem*> validItems;
foreach (QGraphicsItem* item, items) {
    if (!item) continue;
    if (item->type() == NexusBlockItem::Type) {
        int nodeCenterY = item->pos().y() + (item->boundingRect().height()/2.0);
    }
}

Qt为此提供了一个很好的功能:qSort()

bool itemLess(const QGraphicsItem* item1, const QGraphicsItem* item2)
{
    return item1->sceneBoundingRect().center().y() < item2->sceneBoundingRect().center.y();
}
qSort(validItems.begin(), validItems.end(), itemLess);

注意1:您可以使用std::sort()而不是qSort()

注意2:您可以使用函子lambda来比较项,而不是itemLess()函数。

注意3qSort()std::sort()都使用快速排序算法。

编辑

正如vicrucann所提到的,Qt文档建议使用std::sort()而不是qSort()