PDA

View Full Version : How to properly show image in QGraphicsView?



theateist
18th April 2019, 22:07
I'm trying to show an image in QGraphicsView, but for some reason the top-right corner starts in the middle of the QGraphicsView.
Also, how to make it fit the QGraphicsView?

Here's my code:


Mat frameMat;
videoReader >> frameMat;

_graphicsScene = make_unique<QGraphicsScene>(0, 0, 300, 300);
ui.graphicsView->setScene(_graphicsScene .get());
_graphicsScene ->setBackgroundBrush(Qt::blue);

QImage qImg(frameMat.data, frameMat.cols, frameMat.rows, frameMat.step, QImage::Format_RGB888);
auto pixImg = QPixmap::fromImage(qImg);

auto item = new QGraphicsPixmapItem(pixImg);
_graphicsScene ->addItem(item);

Here what I get when I run my code:
13084

ChrisW67
18th April 2019, 23:53
The scene is displayed in the view at a 'natural' scale by default. If the view has more space available than the scene covers then you will see the background around the image.
Your code does not show how the view is sized.

You probably want to experiment with:


ui.graphicsView->fitInView(_graphicsScene ->sceneRect(), Qt::KeepAspectRatio);

theateist
19th April 2019, 16:55
I tried to use
_graphicsScene->setSceneRect(0, 0, 500, 500); but it seems moves the image up and left. If I do
_graphicsScene->setSceneRect(200, 200, 500, 500); it moves the image top and left beyond the actual window. Why?

ChrisW67
20th April 2019, 07:05
The scene coordinate system and the view coordinate system are not the same thing. There is a coordinate transformation between the two systems. That transformation maps coordinates in the scene onto view coordinates to make the scene visible in the view. It may be the entire scene, part of the scene, a rotated version etc. that ends up being visible. When the entire scene can fit in the view the QGraphicsView::alignment() comes into play: by default this centres. Assuming this is the case in your code then:


view->setAlignment(Qt::AlignTop | Qt::AlignLeft);

may help