Question

I'm trying to learn Qt by developing a simple GUI. Part of what I need to do is add a rectangle to one of three QGraphicsView areas I have made. I used the following code

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow){
    ui->setupUi(this);
    QGraphicsRectItem rect;
    rect.setRect(10,10,10,10);
    ui->graphicsView->scene()->addRect(rect.rect());
}

However while this compiles just fine, my program does not run at all, in fact upon reaching the last line it immediately exits, does anyone know what the issue could be? (Apologies for formatting, first time poster)

Was it helpful?

Solution

You need to set a scene to your QGraphicsView first:

ui->graphicsView->setScene(new QGraphicsScene);

Right now ui->graphicsView->scene() is returning a null pointer.

QGraphicsView::scene(): Returns a pointer to the scene that is currently visualized in the view. If no scene is currently visualized, 0 is returned.

Also, instead of creating a QGraphicsRectItem and using its rect() method to return a QRect object that you will use in QGraphicsScene::addRect(), you should just create a QRect object and use that:

QRect rect(10,10,10,10);
ui->graphicsView->scene()->addRect(rect);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top