I am trying to modify the code from a tutorial on QGraphicsView
found here
Basically what it does is create some objects derived from QGraphicsItem
, which are confined in a square whose dimensions are the same as the limits of the scene. These objects when they meet the limits of the scene bounce, and when they collide with each other they change color.
Well, my modification intends that instead of changing color, they disappear, that is, I want to remove them from the scene. To do this I modify the original function:
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rect = boundingRect();
// basic collision detection
if(scene()->collidingItems(this).isEmpty())
{
// no collision
QPen pen(Qt::green, 5);
painter->setPen(pen);
}
else
{
// collision !!!
QPen pen(Qt::red, 5);
painter->setPen(pen);
// set the position
doCollision();
}
painter->drawEllipse(rect);
}
For this:
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rect = boundingRect();
// basic collision detection
if(scene()->collidingItems(this).isEmpty())
{
// no collision
QPen pen(Qt::green, 5);
painter->setPen(pen);
}
else
{
// collision !!!
EliminarItem(); //<----Esta es la unica modificacion
QPen pen(Qt::red, 5);
painter->setPen(pen);
// set the position
doCollision();
}
painter->drawEllipse(rect);
}
(Basically the modification is to make a function call EliminarItem()
on collision)
And this function EliminarItem()
does the following:
void MyItem::EliminarItem()
{
for (QGraphicsItem* i : scene()->collidingItems(this))
{
MyItem* itemBorrar = dynamic_cast<MyItem*>(i);
if (itemBorrar)
{
//scene()->removeItem(itemBorrar);
//scene()->update(itemBorrar->boundingRect());
//delete itemBorrar;
qDebug()<<itemBorrar;
}
}
}
Well, the lines are commented out because they give me the error. The item to delete exists, as shown in qDebug()
, but the program crashes and exits.
I do not put all the code because it is copied from the tutorial, but if necessary I add it.
The problem is that you are trying to make a node delete itself...
The person in charge of doing this task cannot be the item itself because it cannot delete itself since by doing so you create inconsistencies in memory:
EliminarItem
continues to execute... but itsthis
points to a deleted object (any use of it, implicit or explicit, will be harmful)paint
will also continue its execution with the same result (any access to itthis
will be destructive)You need an external element to point to that object should be deleted. In this case it may be the
Dialog
(quick fix), although it is best to create a class that would act as the scene manager:Dialog.h
Dialog.cpp
MyItem.h
MyItem.cpp