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();
}
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();
}
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.