PDA

View Full Version : Scaling a portion of an image to zoom into in QGraphicsView



Sergex
13th October 2011, 23:29
Hello,

I am using the Graphics framework to show images on the screen with a view, scene and items. I implemented a rubberband as well to "draw" rectangles on top of those images for the purpose of selecting a piece of the image to zoom into.

So what I want is that when I make a selection of a subarea of my image currently fully displayed in my view, (clicking and holding the mouse, dragging and releasing to make the rubberband rectangle), I want to be able to now see only the selected area in my whole view, so basically have it zoom in to the portion I selected and fit in my viewport only the selected portion, and now of course the scroll bars will appear since the image doesn't fit in the view.

I'm having a rough time "connecting" or mapping my selected rectangle in the image to calculate how much to scale the image and to have the view display the correct area that I chose.
Can someone please help me out on what steps do I need to do for this task?

I was first thinking to get the coordinates of the rubberband rectangle through (Inside my mouseDoubleClickEvent):

m_rubberband->pos().x() //but in fact what x coordinate does that give me? The topleft corner in this case?
m_rubberband->pos().y()


Somehow I need to calculate how much of the image I selected to be able to scale it accordingly? Then the problem of how to make the viewport display correctly what I selected is giving me a hard time..
Any help will be greatly appreciated.

Thank you!

Spitfire
17th October 2011, 13:56
Assuming that you have a rect you want to display (from mouse press/release events) then simplest thing to do is to use:
QGraphicsView::fitInView ( const QRectF& rect, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio )You can use Qt::KeepAspectRatio if that's what you want.

Also when getting top-left and bottom-right points for the rectangle you should map them to sceene coordinates:
void ZoomableView::mousePressEvent( QMouseEvent* e )
{
selectedRect.setTopLeft(this->mapToScene(e->pos()));
}

void ZoomableView::mouseReleaseEvent( QMouseEvent* e )
{
selectedRect.setBottomRight(this->mapToScene(e->pos()));

this->fitInView(selectedRect, Qt::KeepAspectRatio);
}
You can also disable the scroll bars if you don't want them:
QGraphicsView::setHorizontalScrollBarPolicy(Qt::Sc rollBarAlwaysOff);
QGraphicsView::setVerticalScrollBarPolicy(Qt::Scro llBarAlwaysOff);