0

I am creating a graphics scene in Qt widgets application. The application runs successfully but no graphics scene is displayed.

The code that I am using to create scene is:

cadviewer::cadviewer(QGraphicsScene *parent) :
QGraphicsScene(parent)
{
QGraphicsScene scene;
scene.addLine(10,10,20,20);
QGraphicsView view(&scene);

view.show();
qDebug() << "cadviewer";
} 

The call to the above class is made in another class. The code for the same is:

graphicsarea::graphicsarea(QWidget *parent) :
QWidget(parent),
ui(new Ui::graphicsarea)
{
ui->setupUi(this);
cadviewer viewer;
qDebug() << "graphicsarea";
}

The qDebug used in the two classes is working.

I am unable to figure out what's missing. Do help me out how to display the graphics scene in the main window?

Kamalpreet Grewal
  • 822
  • 1
  • 13
  • 28
  • 1
    you are deleting the QGraphicsScene when you exit the cadviewer constructor (which in turn also gets deleted when you leave the graphicsarea constructor, also creating isn't enough it needs to be added to the graphicsarea – ratchet freak Jul 03 '14 at 10:05
  • Doesn't creating imply it would be added to the scene? If not, how do you add it to the graphicsarea? – Kamalpreet Grewal Jul 03 '14 at 10:13
  • you can add the graphicscene to a layout and this layout to the area. I update my Answer. – Matthias Jul 03 '14 at 10:55

2 Answers2

0

I will not repeat what ratchet freak told you. One of the solution to overcome this problem is just to add QGraphicsScene scene; and QGraphicsView view; in your class attributes.

That way, at the end of the constructor, they will still be alive and displayed !

Martin
  • 877
  • 8
  • 20
0

You have declared only a local Variable in the constructor. After the Program leaves the constructor your "cadviewer viewer" will be deleted.

graphicsarea::graphicsarea(QWidget *parent) :
QWidget(parent),
ui(new Ui::graphicsarea)
{
ui->setupUi(this);
cadviewer viewer; //delete after constructor
qDebug() << "graphicsarea";
}

Try to use it as a class attribute/member. A Class Member is still alive when the Application leaves the constructor.

Update:

Here is a little example how to add your graphicscene to the area:

QLayout* testLayout = new QVBoxLayout();
cadviewer* view = new cadviewer();
layout->addWidget(view);
graphicsarea* area = new graphicsarea();
area->setLayout(testLayout);
area->show();

Other layouts are possible too.

Matthias
  • 463
  • 1
  • 7
  • 12