qt - 当 QGraphicsScene::addPixmap 只接受 const QPixmap 时如何使用它?

标签 qt qgraphicsview qgraphicsscene qimage qpixmap

我想通过QGraphicsScene显示一些QImage,我的代码非常简单:

ma​​inwindow.h

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

ma​​inwindow.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/

相关文章:

c++ - C++ 中 static 和 global 的替代品?

c++ - 理解 QGraphicsItemboundingRect 和 shape 方法之间的交互

Qt 4.7.4 - 在 QGraphicsItem 像素图中使透明像素可点击(展开点击框)

python - PySide QGraphicsView 大小

python - 获取自定义 Qt QGraphicsView 以显示在使用 Qt Designer 制作的表单中

qt - QGraphicsView:如何使橡皮筋选择仅出现在鼠标左键上?

c++ - QGraphicsPathItem 重叠的半透明路径变得更加不透明

android - 如何将qt资源添加到android APK文件中?

c++ - 在 QTcpServer 服务器端出现 : The remote host closed the connection

qt - QGLWidget 比 QWidget 慢