Reputation: 15
I have used and modified the sample code below:
void MyScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
myPath = new QGraphicsPathItem();
previous = event->scenePos();
QPainterPath p;
p.moveTo(previous);
myPath->setPath(p);
this->addItem(myPath);
}
void MyScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(myPath)
{
QPainterPath path = myPath->path();
previous = event->scenePos();
path.lineTo(previous);
myPath->setPath(path);
}
}
it is part of a simple 'sketch system'. What I find strange is that the pointer:
QGraphicsPathItem *myPath;
does not take a constructor or allow:
myPath = new QGraphicsPathItem(this); // this code will fail - why?
I would have thought that would aid the clean up / deletion of the pointer. Why does this not leak memory? Or does it? I have used Valgrind from within QTCreator and it doesn't seem to show any memory leak. Should I have in some location:
delete(myPath); // is this needed?
Can anybody explain or point to a concise explanation of when delete is needed please specifically within QT. I am looking at QPointer and QSharedPointer, probably a better approach.
I find Valgrind difficult to use on the command line with a QTCreator created application as it seems to get confused with the GUI objects being created etc and spits out hundreds and hundreds of lines. From within QTCreator I have tested valgrind with simple cases and it just points to the correct lines and nothing else - far far easier. Without the line above:
delete(myPath); // is this needed?
Valgrind doesn't seem to show a memory leak. Why?
How much can I trust Valgrind from within QtCreator?
Upvotes: 0
Views: 396
Reputation: 15334
I'm no expert on Qt but I assume MyScene
inherits from QGraphicsScene. In which case, addItem() takes ownership of myPath
and will delete
it when needed.
As long as you have passed ownership of the QGraphicsPathItem
to some other object you don't have to delete it but up to that point you are responsible for the memory. Watch out for code paths where addItem()
is not called because then you might need to call delete
. For example, if an exception is thrown.
This kind of pattern is a little out dated but is still common in scene graph based graphics frameworks.
Upvotes: 1