Question

I'd like to display some QImage through QGraphicsScene, my code's very straightforward:

mainwindow.h

QImage *sourceImage;
QGraphicsView *imageView;
QGraphicsScene *imageScene;

mainwindow.cpp

imageScene = new QGraphicsScene;
imageView = new QGraphicsView;
imageView->setScene(imageScene);

sourceImage = new QImage;
sourceImage.load(":/targetimage.png");
imageScene.addPixmap(QPixmap::fromImage(sourceImage));

And then the complier points out exactly what I did wrong: QGraphicsScene::addPixmap accepts only const QPixmap as argument, and I was trying to convert QImage to const QPixmap, which is not allowed because QPixmap::fromImage within only accept const QImage, like a const hell.

The official documentation on this method doesn't make much sense to me either, if I'd like to make for example, an image viewer, and during runtime I'd sure load different images into QImage sourceImage, and how can I accomplish that using a const QImage?

This problem has been agonizing, thanks for any advice. Moreover could you light me a bit if there's any vision on the philosophical reason why guys in Qt make these methods const?

Was it helpful?

Solution

Try

imageScene.addPixmap(QPixmap::fromImage(*sourceImage));

Some advice:

there is no need to allocate the QImage on the heap (using new). Use:

QImage sourceImage;

Then you do not need to dereference the pointer when calling QPixmap::fromImage

Just to clarify: the constness has nothing to do with the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top