Using a QGraphicsView Widget



  • Maybe I am not following the correct workflow, but this has worked on other elements.

    I am using Qt Creator 3.6.1, which has Qt 5.6.0 MSVC 2013 on a Windows PC.

    I added a QGraphicsView widget to the Window form, and I want to draw a rectangle in it.

    In the form's constructor, I put the following code, the last line of which causes a segmentation fault. Note that the rect is a data member of the Form's class. (The first line was already there).

    ui->setupUi(this);
    rect.setRect(10,10,20,30);
    ui->graphicsView->scene()->addItem(&rect);
    

    I also tried putting the rect on the heap like this.

    rect = new QGraphicsRectItem(10,10,20,30);
    ui->graphicsView->scene()->addItem(rect);
    

    Same problem. The Segfault occurs in the addItem call.

    Does the scene need to be allocated? I don't see a setScene method, so I assumed that the framework initialized everything.

    Thoughts?



  • @Mister-Rose Hi! Yes, you need to create the scene, too, and give it to the view:

    QGraphicsScene *scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);
    


  • @Wieland said in Using a QGraphicsView Widget:

    ui->graphicsView->setScene(scene);

    Thank you. Works as expected.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.