Search code examples
c++qtqgraphicsviewqgraphicsscene

QGraphicsScene clear display


I'm new here and i can't solve this thing. I have a QGraphicScene (which at first initializes a Cartesian plane) in which it draw points \ lines with the methods AddLine \ ecc.Everything works.But I want to have a method that delete all "objects" drawn on the scene and reloads the cartesian plane.Any suggestion?

Here you can find my classes:

class draw: public QWidget
{
    Q_OBJECT

private:

    QGraphicsScene scene;
    int x1;
    int y1;
    int x2;
    int y2;

public:
    disegna (QWidget *parent = 0);
    void setdot(QString,QString);
    void setsegment(QString,QString,QString,QString);
    ~disegna(){}
    };

draw::draw(QWidget *parent) : QWidget(parent) { 
    scene.setBackgroundBrush(Qt::white);
    scene.addRect(QRectF(0,0, 600, 200));
    scene.addLine(0, 100 ,600, 100);
    scene.addLine(300, 0 ,300, 200);
    scene.addEllipse(297.5,97.5,5,5,QPen(), QBrush(Qt::red));

    int i=0;
    for (int a=0;a<120;a++) {
        scene.addLine(i+5, 98 ,i+5, 102);
        i=i+5;
    }

    int j=0;
    for (int a=0;a<40;a++) {
        scene.addLine(298,j+5,302,j+5);
        j=j+5;
    }

    QGraphicsView * view = new QGraphicsView(&scene,this);
    view->show();
}

void draw::setdot(QString x1,QString y1){
    scene.addEllipse(x1.toInt()+298, 98-y1.toInt(),4,4,QPen(), QBrush(Qt::blue));
}

void draw::setsegment(QString x1,QString y1,QString x2,QString y2) {
    scene.addLine(x1.toInt()+300, 100-y1.toInt(),x2.toInt()+300, 100-y2.toInt(),QPen());
    scene.addEllipse(x1.toInt()+298, 100-y1.toInt(),4,4,QPen(), QBrush(Qt::blue));
    scene.addEllipse(x2.toInt()+298, 100-y2.toInt(),4,4,QPen(), QBrush(Qt::blue));
}

Solution

  • For cleaning the scene, did you tried the clear method ?

    If you want to clear and redraw, I suggest you to move the drawing code from your constructor to a method. Then you can call clear then your drawing method.

    Hope it helps