Search code examples
qtqimageqgraphicsscene

QImage in a QGraphics scene


I am quite new to Qt. I am having troubles in inserting a QImage to a scene. Could somebody please tell me how to add a QImage to a QGraphicsScene?


Solution

  • For this you would use a QGraphicsPixmapItem that you add to the scene like any other QGraphicsItem.

    The QGraphicsPixmapItem can be initialized with a QPixmap which is a device-dependent representation of a bitmap and you can get it from a QImage for example with the static function QPixmap::fromImage().

    Update (example code)

    #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();
    }