2

I am drawing a polygon on qgraphicsscene using QPainterPath. However after sometime when I want to delete the path I am unable to delete it. Can someone tell me how to delete/erase the drawn path. I am trying the following code.

 In header File:

 QGraphicsScene *scene;
 QGraphicsPixmapItem *m_pixItem;
 QPainterPath m_pathTrack;
 QPolygon m_qpolygon;


 In cpp file

void MyClass::AddPath()
{
  //Slot to add path to the scene

 QImage l_img("Path");
 graphicsView->setScene(&scene);
 m_pixtemItem->setPixmap(QPixmap::fromImage(image));

 //Code here to Adding points to polygon. The points are coming at regular interval
 m_qpolygon.append(Point);

 m_pathTrack.addPolygon(m_qpolygon);
 scene.addPath(m_pathTrack);
}

// In slot to delete path

 void MyClass::DeletePath()
 {
    //I tried doing this but the path does not erase

    m_pathTrack = QPainterPath();
 }

Thank You.

Sid411
  • 703
  • 2
  • 9
  • 25

2 Answers2

3

Just retain a pointer on QGraphicsPathItem create when adding your path

QGraphicsPathItem* pathItem = scene.addPath(m_pathTrack);

Then you will be able to remove it from scene:

scene->removeItem(pathItem);

EDIT (credits to thuga):

If you don't plan to put again this item in your scene, you can free its memory once you have removed it from the scene.

scene->removeItem(pathItem);
delete pathItem;
epsilon
  • 2,849
  • 16
  • 23
  • 1
    You have to remember to delete it too, if don't need it anymore. – thuga Jun 23 '14 at 11:05
  • @thuga you are right. I did not mention it as the pathItem will be parented to the scene and will not be leaked. But I will edit this advice. Thanks :) – epsilon Jun 23 '14 at 11:09
  • Thanks for the reply. I am trying this but it is not deleting the entire path that is drawn. Instead a few initial points are getting deleted. – Sid411 Jun 23 '14 at 11:42
  • I got it. Thanks for the help. I changed the implementation a bit. I used scene.addItem() to add the path and then pathItem.setPath() and setPen. Thanks again :) – Sid411 Jun 23 '14 at 12:27
  • 1
    Is there a reason why you access one time scene via `.` and one time via `->`? I also get an error with the note "no known conversion for argument 1 from 'QGraphicsPathItem*' to 'QGraphicsItem*'" When trying to implement your solution. Am I missing something? – dhein Nov 06 '15 at 16:51
  • Also why you have to delete content that wasn't allocated by you, but by an API-function? – dhein Nov 06 '15 at 16:53
0

Remember to include the corresponding head file, QGraphicsItem. Or you will not able to call the function.

liu km
  • 1
  • 3
lovenjak
  • 35
  • 5