I am quite new to Qt. I am having troubles in inserting a QImage
to a scene. Could somebody please tell me how to add a QImage
to a QGraphicsScene
?
QImage in a QGraphics scene
Asked Answered
For this you would use a QGraphicsPixmapItem
that you add to the scene like any other QGraphicsItem
.
The QGraphicsPixmapItem
can be initialized with a QPixmap
which is a device-dependent representation of a bitmap and you can get it from a QImage
for example with the static function QPixmap::fromImage()
.
Update (example code)
#include <QtGlobal>
#if QT_VERSION >= 0x050000
#include <QtWidgets>
#else
#include <QtGui>
#endif
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QImage image("test.png");
QGraphicsPixmapItem item( QPixmap::fromImage(image));
QGraphicsScene* scene = new QGraphicsScene;
scene->addItem(&item);
QGraphicsView view(scene);
view.show();
return a.exec();
}
Hi, I tried this solution but it was not working for me. I have pasted my code below. –
Jeopardize
Hi, I tried this solution but it was not working for me. I have pasted my code below. QGraphicsScene scene; QImage* qimage = new QImage("./IMG_2938.JPG"); QGraphicsPixmapItem pixmapItem(QPixmap::fromImage(*qimage)); scene.addItem(&pixmapItem); QGraphicsView view(&scene); view.show(); It doesn't show the image, just a window, but it just shows an emptybox.Hope someone can answer. –
Jeopardize
I added some example code to my answer. This works for me (it is very close to what you posted). So two things come to mind: 1. Are you sure the image is found and loaded correctly? (check QImage::isNull() or use QImage::load() explictly and check the return value) 2. If you put objects on the stack instead of the heap, make sure they are still alive when they are used. –
Proctoscope
The code in the example will not work after the function containing
item
returns, because item
is destructed upon returning. –
Wozniak error: variable 'QGraphicsPixmapItem item' has initializer but incomplete type QGraphicsPixmapItem item( QPixmap::fromImage(image));
–
Boeschen The example was written for Qt4; I assume you are using Qt5 where the widgets got split of into their own module. I changed the example to compile for both cases. –
Proctoscope
wouldn't the addPixmap() function of QGraphicsScene work? –
Neddy
As @Neal suggested, addPixmap works much simpler and where the QGraphicsPixmapItem would not work for me for some unknown reason. Assuming you have a QGraphicsScene
, QGraphicView
and rest of program set up the below code will just display the image:
QString filename = "C:/image.png";
QImage image(fileName);
scene->addPixmap( QPixmap::fromImage(image));
© 2022 - 2024 — McMap. All rights reserved.