Show Qimage on graphicsView
-
Hello, Im trying to show a QImage into qgraphicsView, but it never works, I tried the following code:
QGraphicsScene *scene = new QGraphicsScene; QImage image("path/QtImage.jpg"); QGraphicsPixmapItem item(QPixmap::fromImage(image)); scene->addItem(&item); ui->graphicsView->setScene(scene);
I fist create a scene,then trnasform the image into a Qpixmap item and add item to scene, then I set the scene into graphicsView. I can not see anything.
Can you help me please?
-
@jss193 said in Show Qimage on graphicsView:
QGraphicsPixmapItem item(QPixmap::fromImage(image));
You're creating the object on the stack so it will get deleted once the function exits...
-
Hi,
Here's an example:
void MyWidget::myFunction() { QImage image("path/QtImage.jpg"); QGraphicsPixmapItem item(QPixmap::fromImage(image)); } // << Here both image and item cease to exist.
-
They are saying you should allocate the
QGraphicsPixmapItem
on the heap:QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
The scene takes ownership of it:
-
@jss193 said in Show Qimage on graphicsView:
Thank you, I know that but what I showed is not part of a function, is part of pushing a button, these are the actions inside that code, but it remanins not showing any image.
Thank you
A slot is still a function and the same logic applies to it as my shorten example.
Do as @Andy-M wrote and allocate the item on the heap.