views:

387

answers:

1

This is probably something very obvious, but I have a new to Qt and can't figure it out. I have a simple MainWindow which has one button. When that button is clicked I want to create a QGraphicsScene, add a few lines and then show that in the Window. However when I run this code in a Window it does not show up.

BUT, if I run this as a QApplication, it shows up just fine. What am I missing?

Here is the code in the MainWindow:

void TheDrawings::drawScene() {
 qDebug() << "Setting up Scene";

 QGraphicsScene scene(QRect(-50, -50, 400, 200));

 QPen pen(Qt::red, 3, Qt::DashDotDotLine);

 QGraphicsRectItem *rectItem = new QGraphicsRectItem(QRect(-50, -50, 400,
   200), 0, &scene);
 rectItem->setPen(pen);
 rectItem->setBrush(Qt::gray);

 QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(
   "Amit Bahree", 0, &scene);
 textItem->setPos(50, 0);

 QGraphicsEllipseItem *eclipseItem = new QGraphicsEllipseItem(QRect(170, 20,
   100, 75), 0, &scene);
 eclipseItem->setPen(QPen(Qt::darkBlue));
 eclipseItem->setBrush(Qt::darkBlue);

 QGraphicsPolygonItem *polygonItem = new QGraphicsPolygonItem(QPolygonF(
   QVector<QPointF> () << QPointF(10, 10) << QPointF(0, 90)
     << QPointF(40, 70) << QPointF(80, 110) << QPointF(70, 20)),
   0, &scene);
 polygonItem->setPen(QPen(Qt::darkGreen));
 polygonItem->setBrush(Qt::yellow);

 qDebug() << "Setting up the view";
 QGraphicsView view;
 view.setScene(&scene);
 view.show();

}

+2  A: 

your QGraphicsView needs a centralwidget of the mainwindow (or whatever widget you want to put it on top of) to be set as a parent. Also you need to "new" your view and scene objects to put them on the heap so they don't get destroyed once drawScene finishes. See of following changes to your code would work fine for you:

QGraphicsScene* scene = new QGraphicsScene(QRect(-50, -50, 400, 200));
...
QGraphicsView* view = new QGraphicsView(ui->centralWidget);
view->setScene(scene);
view->setGeometry(QRect(50, 50, 400, 200));
view->show();

hope this helps, regards

serge_gubenko
not sure that you actually need a parent for the view, but you definitely need to allocated on the heap (i.e. new).
e8johan
Hi Guys, perfect that worked. I think I understand what was going wrong - as this was not on the heap, it was getting cleaned up before it could repaint.e8johan, if I don't set the parent then it shows up as a new widget and I get two windows instead of one. I think I might need to setup another container widget for this.
bahree