0

Hi iv looked at other questions and solutions for this but none seem to help for my specific problem.

Im simply trying to add a picture to my GraphicsView that i have added using Qt designer

.cpp

void test::populateScene()
{
     QImage image(":/images/myFile.png");
     QGraphicsPixmapItem item(QPixmap::fromImage(image));
     QGraphicsScene *scene = new QGraphicsScene;
     scene->addItem(&item);
     ui->graphicsView->setScene(scene); 
}

i have the necessaary includes but when i click run the program just puts up a not responding message straight away

i have no compiler errors just hit run and then then get test.exe is not responding

any ideas, this seems like it should be really simple but i cant work out why this isnt right (mainly due to no compiler errors to look through and find the cause of the crash)

AngryDuck
  • 4,358
  • 13
  • 57
  • 91

2 Answers2

0

[SOLVED]

    QImage image(":/images/myFile.png");
    QGraphicsScene *scene = new QGraphicsScene();
    scene->addPixmap(QPixmap::fromImage(image));
    scene->setSceneRect(0,0,image.width(),image.height());
    ui->graphicsView->setScene(scene);

No other solution i found here or elsewhere for getting an image into a graphicsview have worked so i will post this to help others now my problem is solved feel free to ask questions

Community
  • 1
  • 1
AngryDuck
  • 4,358
  • 13
  • 57
  • 91
  • Well that's no good because in your header file you declare QGraphicsScene *scene as a member variable. This is bound to cause problems. The second line of this solution should be `scene = new QGraphicsScene;` – koan Apr 16 '13 at 14:07
  • oh sorry took that out just forgot to update my initial question code – AngryDuck Apr 16 '13 at 14:10
0

You have to allocate your new item on the heap!

http://harmattan-dev.nokia.com/docs/library/html/qt4/qgraphicsscene.html#addItem

Adds or moves the item and all its childen to this scene. This scene takes ownership of the item.

The description of the function is quite clear: it will need pointer that is valid for more that the scope of your function, so that it can take ownership of it.

void test::populateScene()
{
     QImage image(":/images/myFile.png");
     QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
     QGraphicsScene *scene = new QGraphicsScene;
     scene->addItem(item);
     ui->graphicsView->setScene(scene); 
}
Gui13
  • 12,993
  • 17
  • 57
  • 104
  • Thanks iv posted my answer below if you saw....which works only difference is im adding a pixmap to the scene instead of an item that is just a pixmap – AngryDuck Apr 16 '13 at 14:03
  • Yep sure, but if you want to really understand what happens there, you'll have to figure out why using the address of an object that is local to your function make the program crash. – Gui13 Apr 16 '13 at 14:06