JustinBlaber
JustinBlaber

Reputation: 4650

Dynamically add QGraphicsEllipseItems

Basically, each time I click on a graphicsview, I'd like a new QGraphicsEllipseItem to appear. The number is up to the user. Also, I'd like to query all of them in the end with pos() to get all their positions. The number of ellipses is not known before hand and their positions are movable by the ItemIsMovable flag. Anyone know how could I do this?

I could make an array of pointers to the graphicsitem class but that would possibly waste memory and limit the number of ellipses I can make. Thanks.

Upvotes: 1

Views: 1328

Answers (1)

leemes
leemes

Reputation: 45675

You can add as much items as you want to the scene (as long as there is free memory space, of course):

myGraphicsScene->addEllipse(rect, pen, brush);

In order to add items for each click, reimplement the mousePressEvent of the QGraphicsView:

void MyGraphicsView::mousePressEvent(QMouseEvent *e)
{
    int rx = 10; // radius of the ellipse
    int ry = 20;
    QRect rect(e->x() - rx, e->y() - ry, 2*rx, 2*ry);
    scene()->addEllipse(rect, pen, brush);

    // call the mousePressEvent of the super class:
    QGraphicsView::mousePressEvent(e);
}

You don't have to store the pointers by yourself. When you want to query some piece of information of all items in the scene, just loop over the list of items provided by the scene:

foreach(QGraphicsItem *item, myGraphicsScene->items())
    qDebug() << "Item geometry =" << item->boundingRect();

(or for the position only: item->pos())

If you want to query a piece of information of a subclass of QGraphicsItem, you can cast the item to your type using Qt's QGraphicsItem casting mechanism, which returns a null pointer if the item isn't of the requested type. After checking the pointer to be not null, you can access your own member:

foreach(QGraphicsItem *item, myGraphicsScene->items())
{
    MyDerivedItem *derivedItem = qgraphicsitem_cast<MyDerivedItem*>(item);
    if(derivedItem) // check success of QGraphicsItem cast
        qDebug() << derivedItem->yourCustomMethod();
}

Upvotes: 2

Related Questions