【问题标题】:How to sort a QList of QGraphicsitem by coord x or coord y?如何按坐标 x 或坐标 y 对 QGraphicsitem 的 QList 进行排序?
【发布时间】:2019-04-11 03:10:00
【问题描述】:

我正在尝试找到通过这些项目的 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());
}

【问题讨论】:

    标签: c++ qt qgraphicsscene qgraphicsitem


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多