Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 824
Tharanga Avatar asked May 11 '11 06:05

Tharanga


2 Answers

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();
}
like image 177
Steffen Avatar answered Nov 08 '22 06:11

Steffen


As @Neal suggested, addPixmap works much simpler and where the QGraphicsPixmapItem would not work for me for some unknown reason. Assuming you have a QGraphicsScene, QGraphicView and rest of program set up the below code will just display the image:

QString filename = "C:/image.png";
QImage image(fileName);
scene->addPixmap( QPixmap::fromImage(image)); 
like image 2
EddyWD Avatar answered Nov 08 '22 07:11

EddyWD