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
?
Asked
Active
Viewed 2.7k times
15

GraphicsMuncher
- 4,583
- 4
- 35
- 50

Tharanga
- 2,007
- 4
- 32
- 50
2 Answers
19
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();
}

Steffen
- 2,888
- 19
- 19
-
Hi, I tried this solution but it was not working for me. I have pasted my code below. – Tharanga May 11 '11 at 11:16
-
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. – Tharanga May 11 '11 at 11:20
-
1I 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. – Steffen May 11 '11 at 11:56
-
1The code in the example will not work after the function containing `item` returns, because `item` is destructed upon returning. – bcmpinc May 19 '14 at 09:13
-
`error: variable 'QGraphicsPixmapItem item' has initializer but incomplete type QGraphicsPixmapItem item( QPixmap::fromImage(image));` – Patrizio Bertoni Dec 16 '15 at 08:29
-
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. – Steffen Dec 16 '15 at 08:59
-
wouldn't the addPixmap() function of QGraphicsScene work? – Neal Feb 15 '16 at 03:55
2
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));

EddyWD
- 197
- 2
- 15