geometry of QGraphicsRectItem

1.9k views Asked by At

I have a qgraphicsRectItem drawn on a qgraphicsScene. With mouse events, it's being moved over the scene, resized and repositioned, ie, select the item, mousePress and mouseMove. How can I get the geometry of that qgraphicsRectItem boundingRect, pos wrt scene on mouseReleaseEvent? There's a image on scene, and a boundingrect of qgraphicsRectItem is drawn on the scene, then i need to get qrect for cropping that portion of image within the bounding rect.

1

There are 1 answers

2
eyllanesc On BEST ANSWER

You have to use mapRectToScene() of the items:

it->mapRectToScene(it->boundingRect());

Example:

#include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>

#include <QDebug>

class GraphicsScene: public QGraphicsScene{
public:
    using QGraphicsScene::QGraphicsScene;
protected:
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
        print_items();
        QGraphicsScene::mouseReleaseEvent(event);
    }
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event){
         print_items();
        QGraphicsScene::mouseMoveEvent(event);
    }
private:
    void print_items(){
        for(QGraphicsItem *it: items()){
            qDebug()<< it->data(Qt::UserRole+1).toString()<< it->mapRectToScene(it->boundingRect());
        }
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsView w;
    GraphicsScene scene(0, 0, 400, 400);
    w.setScene(&scene);

    QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(-10, -10, 20, 20));
    item->setData(Qt::UserRole+1, "item1");
    item->setBrush(QBrush(Qt::green));
    item->setFlags(QGraphicsItem::ItemIsMovable);

    QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(0, 0, 20, 20));
    item2->setData(Qt::UserRole+1, "item2");
    item2->setBrush(QBrush(Qt::blue));
    item2->setFlags(QGraphicsItem::ItemIsMovable);

    scene.addItem(item);
    scene.addItem(item2);
    w.show();

    return a.exec();
}