我想通过QGraphicsScene
显示一些QImage
,我的代码非常简单:
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));
然后编译器准确地指出我做错了什么:QGraphicsScene::addPixmap
仅接受 const QPixmap
作为参数,我试图将 QImage
转换为 const QPixmap
,这是不允许的,因为 QPixmap::fromImage
内只接受 const QImage
,就像一个 const
hell 。
official documentation这种方法对我来说也没有多大意义,如果我想制作一个图像查看器,并且在运行时我肯定会将不同的图像加载到QImage sourceImage
中,以及如何我可以使用 const QImage
来实现这一点吗?
这个问题一直困扰着我,谢谢大家的建议。此外,如果 Qt 中的人将这些方法设为 const 的哲学原因有什么远见,您能否给我一些启发?
最佳答案
尝试
imageScene.addPixmap(QPixmap::fromImage(*sourceImage));
一些建议:
不需要在堆上分配QImage(使用new)。 使用:
QImage sourceImage;
那么调用QPixmap::fromImage
时就不需要取消引用指针
只是为了澄清:常量与错误无关。
关于qt - 当 QGraphicsScene::addPixmap 只接受 const QPixmap 时如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23212118/