开发者

QImage in a QGraphics scene

开发者 https://www.devze.com 2023-03-04 20:22 出处:网络
I am quite new to Qt. I am having troubles in inserting a QImag开发者_开发知识库e to a scene. Could somebody please tell me how to add a QImage to a QGraphicsScene?For this you would use a QGraphicsPi

I am quite new to Qt. I am having troubles in inserting a QImag开发者_开发知识库e to a scene. Could somebody please tell me how to add a QImage to a QGraphicsScene?


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


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)); 
0

精彩评论

暂无评论...
验证码 换一张
取 消