1

Both of these code segments load in an image. Code 1, loads an image and has a zoom function and Code 2 is supposed to only load an image. Code 1 works perfectly, but when I tried to simplify it, I lost the load image functionality. For some reason the image is being destroyed before it is made visible.

It seems like it should be fairly straight forward but I can't seem to fix it.

Code 1: (this works but seems overly complicated)

#include <QtGlobal>
#if QT_VERSION >= 0x050000
    #include <QtWidgets>
#else
    #include <QtGui>
#endif

int main(int argc,char* argv[])
{
  QApplication app(argc,argv);
  QImage image(":/images/2.png"); 

  QGraphicsScene* scene = new QGraphicsScene();
  QGraphicsView* view = new QGraphicsView(scene);
  QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));

  scene->setBackgroundBrush(QPixmap(":/images/2.png"));
  scene->setBackgroundBrush(image.scaled(100,100,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));

  QGraphicsPixmapItem* pi = scene->addPixmap(QPixmap::fromImage(image).scaledToWidth(50));
  QGraphicsEllipseItem *item2 = new QGraphicsEllipseItem( 0, &scene );

  item2->setRect( -50.0, -50.0, 50, 100.0 );
  scene->addItem(item2);
  view->show();  
  return app.exec();
}

Output of Code 1

Code 2: (this is the simplified version but it is broken)

#include <QtGlobal>

#if QT_VERSION >= 0x050000
    #include <QtWidgets>
#else
    #include <QtGui>
#endif

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  QImage myImage;
  myImage.load("2.png");

  QGraphicsScene* scene = new QGraphicsScene();
  QGraphicsView* view = new QGraphicsView(scene);
  QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(myImage));

  scene->addItem(item);
  view->show();

  return app.exec();
}

Output of Code 2

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Aborg
  • 11
  • 2
  • 1
    There's quite a lot of difference between the two - e.g. where you load your file from, and setting the scene background. You should be able to move incrementally from one to the other until you find the change that breaks it. Start by checking whether `myImage.isNull()` immediately after `load()`. – Toby Speight Aug 10 '16 at 16:49
  • Can you elaborate more on why it is broken? – nbryans Aug 10 '16 at 17:17

1 Answers1

0

Do you want to load the same image in both versions of the code? If yes, you should as well use the same path to this image.

In the first version of your code you use ":/images/2.png" as your image source. This is a path pointing to a file in the Qt Resource System. You probably have a .qrc file in your project containing your desired image file.

You should use the same path in the second version and have the same .qrc file compiled into the project.

MrBolton
  • 47
  • 6