Qt5 C++ QGraphicsView: Images don't fit view frame

后端 未结 4 2112
挽巷
挽巷 2020-12-18 21:31

I\'m working on program which shows user some picture that is selected by him. But there is a problem because I would like to fit this picture in QGraphicsView\'s frame and

4条回答
  •  暖寄归人
    2020-12-18 21:59

    The reason you're not seeing your image as you want it is because the QGraphicsView function fitInView does not do what you think it does.

    It ensures that the object fits inside the viewport, without any overlap of the borders of the view, so if your object was not in the view, calling fitInView will cause the view to move / scale etc to ensure that the object is completely visible. Also, if the viewport is too small for the area provided to fitInView, nothing will happen.

    So, to get what you want, map the extents of the GraphicsView coordinates to the GraphicsScene and then set the image's scene coordinates to those. As @VBB said, if you stretch the image, it may change the aspect raio, so you can use scaledToWidth on the QPixmap.

    Something like this: -

    QRectF sceneRect = ui->graphicsView->sceneRect(); // the view's scene coords
    QPixmap image = QPixmap::fromImage(*image);
    
    // scale the image to the view and maintain aspect ratio
    image = image.scaledToWidth(sceneRect.width());
    
    QGraphicsPixmapItem* pPixmap = scn->addPixmap(QPixmap::fromImage(*image));
    
    // overloaded function takes the object and we've already handled the aspect ratio
    ui->graphicsView->fitInView(pPixmap);
    

    You may find that you don't need the call to fitInView, if your viewport is in the right place and if you don't want it to look pixellated, use an image with a high resolution.

提交回复
热议问题