문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top