在QGraphics场景中的QImage

15

我对Qt还比较陌生。 我在将 QImage 插入场景时遇到了一些麻烦。 请问有人能告诉我如何将 QImage 添加到 QGraphicsScene 中吗?

2个回答

19

为此,您可以使用QGraphicsPixmapItem,并像其他QGraphicsItem一样将其添加到场景中。

QGraphicsPixmapItem可以用QPixmap初始化,它是位图的设备相关表示,例如您可以使用静态函数QPixmap :: fromImage()QImage中获取它。

更新(示例代码)

#include <QtGlobal>

#if QT_VERSION >= 0x050000
    #include <QtWidgets>
#else
    #include <QtGui>
#endif

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QImage image("test.png");

    QGraphicsPixmapItem item( QPixmap::fromImage(image));
    QGraphicsScene* scene = new QGraphicsScene;
    scene->addItem(&item);

    QGraphicsView view(scene);
    view.show();
    return a.exec();
}

1
我在我的回答中添加了一些示例代码。这对我有效(非常接近您发布的内容)。所以有两件事需要考虑:1. 您确定图像被正确找到和加载了吗?(检查QImage::isNull()或显式使用QImage::load()并检查返回值)2. 如果您将对象放在堆栈上而不是堆上,请确保它们在使用时仍然存在。 - Steffen
1
示例中的代码在包含 item 的函数返回后将无法工作,因为 item 在返回时被析构。 - bcmpinc
error: variable 'QGraphicsPixmapItem item' has initializer but incomplete type QGraphicsPixmapItem item( QPixmap::fromImage(image)); - Patrizio Bertoni
这个例子是为Qt4编写的;我假设您正在使用Qt5,其中窗口小部件被拆分成它们自己的模块。我已经修改了示例以便在两种情况下都可以编译。 - Steffen
QGraphicsScene的addPixmap()函数不会起作用吗? - Neal
显示剩余2条评论

2

如@Neal所建议的那样,addPixmap的使用更为简单,在某些情况下QGraphicsPixmapItem无法正常工作。假设您已经设置了QGraphicsSceneQGraphicView和程序余下部分,以下代码将只显示图像:

QString filename = "C:/image.png";
QImage image(fileName);
scene->addPixmap( QPixmap::fromImage(image)); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接