【问题标题】:Remove path from QGraphicsScene从 QGraphicsScene 中删除路径
【发布时间】:2018-04-27 16:57:55
【问题描述】:

我正在使用 QPainterPath 在 qgraphicsscene 上绘制一个多边形。但是,当我想删除路径后,我无法删除它。有人可以告诉我如何删除/擦除绘制的路径。 我正在尝试以下代码。

 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();
 }

谢谢。

【问题讨论】:

    标签: qt qgraphicsscene


    【解决方案1】:

    添加路径时只需在QGraphicsPathItemcreate 上保留一个指针

    QGraphicsPathItem* pathItem = scene.addPath(m_pathTrack);
    

    然后您就可以将其从场景中移除:

    scene->removeItem(pathItem);
    

    编辑(感谢 thuga)

    如果您不打算将该项目再次放入场景中,则可以在将其从场景中移除后释放其内存。

    scene->removeItem(pathItem);
    delete pathItem;
    

    【讨论】:

    • 如果不再需要,你也要记得删除它。
    • @thuga 你是对的。我没有提到它,因为 pathItem 将作为场景的父级并且不会被泄露。但我会编辑这个建议。谢谢:)
    • 感谢您的回复。我正在尝试这个,但它并没有删除绘制的整个路径。相反,一些初始点被删除了。
    • 我明白了。谢谢您的帮助。我稍微改变了实现。我使用 scene.addItem() 添加路径,然后使用 pathItem.setPath() 和 setPen。再次感谢:)
    • 您通过. 访问一次场景并通过-> 访问一次是否有原因?在尝试实施您的解决方案时,我还收到一条错误提示“参数 1 从 'QGraphicsPathItem*' 到 'QGraphicsItem*' 的已知转换”。我错过了什么吗?
    【解决方案2】:

    记得要包含相应的头文件,QGraphicsItem。 否则你将无法调用该函数。

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多