Remove QGraphicsEllipseItems
-
Hi,
I would like to remove previously added ellipses, but I don't know how to do that.
How can I find these items back so they can be removed?this is how I draw the ellipses:
void graphicsView::addPoint(QPointF pos) { qv_points << pos; QGraphicsEllipseItem *newEllipse = new QGraphicsEllipseItem(); double x,y; QPointF point = pos; x = point.x()-2.5; y = point.y()-2.5; newEllipse->setRect(QRectF(x,y,5,5)); newEllipse->setBrush(QBrush(Qt::red, Qt::SolidPattern)); newEllipse->setFlags(QGraphicsEllipseItem::ItemIsMovable | QGraphicsEllipseItem::ItemIsSelectable); //add item to scene scene->addItem(newEllipse); qDebug() << pos; }
-
Hi
The scene keeps a list of items.
https://doc.qt.io/qt-5/qgraphicsscene.html#itemsSomething like ( not compiled )
Loop over all items.
Try to cast it to a QGraphicsEllipseItem
if cast is ok, it IS such item
take it from scene
delete itforeach (QGraphicsItem *item, scene()->items()) { QGraphicsEllipseItem*node = qgraphicsitem_cast<https://doc.qt.io/qt-5/qgraphicsscene.html#removeItem*>(item); if (!node) // it was NOT an QGraphicsEllipseItem item, so skip it continue; // its a QGraphicsEllipseItem scene()->removeItem(node); // take it out ( wont delete, see docs) delete node; // delete it }
https://doc.qt.io/qt-5/qgraphicsscene.html#removeItem
Notice the ownership comment.
-
@hobbyProgrammer
It should :)
Please be aware that we cast it as the scene keeps all items as base pointers (QGraphicsItem *) so
we have to check if right type.Sometimes if having many different types, you can also keep your own list to make it easier to access.
-
@mrjj Hi, just realized that this will probably remove all EllipseItems, but I would like to remove them by position.
So if I press the right mouse button, it gives the position to undoAction and then looks which item is placed there. -
@hobbyProgrammer
Well yes it would if you do the same for all.But in that use case - you can use
https://doc.qt.io/qt-5/qgraphicsscene.html#itemAtTo ask for a item at some position which i guess you can get from the right click.
-
@mrjj it works! thank you so much.
for people watching this:
you can change this:
QGraphicsEllipseItem*node = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
into this:
QGraphicsPolygonItem*node = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
and it will work for a polygon item
or into this:
QGraphicsPixmapItem*node = qgraphicsitem_cast<QGraphicsPixmapItem*>(item);
and it will work for pixmapItems
etc.you can change this line into anything to remove all the object that are that type of graphicsItem