PDA

View Full Version : How to change the content's position in viewport?



aaron
24th March 2009, 07:07
Hi all,
I am a new Qt programmer, and now, I have a question need your help.

I want to zoom in the picture which showing in QGraphicsView. The work flow like below:
press down right button and get the mouse position(mZoomStartPoint) -> move the mouse and draw a rectangle
via QRubberBand class ->release the mouse and get the mouse position(to_point).
and then, scale the picture and show the items which are covered by the rectangle center on the viewport.
the Qt code are:

//MyGraphicsView inherites QGraphicsView


void MyGraphicsView::mousePressEvent(QMouseEvent *e)
{
if(e->button() == Qt::RightButton)
{
mpMouseEvent = e;
setZoomBeginPosition();
}
}

void MyGraphicsView::mouseMoveEvent(QMouseEvent *e)
{
if(e->button() == Qt::RightButton)
{
setZoomMoveTo();
}
}


void MyGraphicsView::mouseReleaseEvent(QMouseEvent *e)
{
if(e->button() == Qt::RightButton)
{
setZoomFinish();
}
}

void MyGraphicsView::setZoomBeginPosition()
{
mZoomStartPoint = mpMouseEvent->pos();
mpRubberBand->setGeometry(QRect(mZoomStartPoint, QSize()));
mpRubberBand->show();
}

void MyGraphicsView::setZoomMoveTo()
{
QPoint to_point = mpMouseEvent->pos();
if(mpRubberBand)
mpRubberBand->setGeometry(QRect(mZoomStartPoint, to_point).mormalized());
}

void MyGraphicsView::setZoomFinish()
{
Qpoint to_point = mpMouseEvent->pos();
int left_x = to_point.x()<mZoomStartPoint.x() ? to_point.x() : mZoomStartPoint.x();
int right_x = to_point.x()>mZoomStartPoint.x() ? to_point.x() : mZoomStartPoint.x();
int top_y = to_point.y()<mZoomStartPoint.y() ? to_point.y() : mZoomStartPoint.y();
int bottom_y = to_point.y()<mZoomStartPoint.y() ? to_point.y() : mZoomStartPoint.y();

if(abs(left_x - right_x)<10 || abs(top_y - bottom_y) < 10)
return;

float x_scale = (viewport()->width()) / (right_x - left_x);
float y_scale = (viewport()->height()) / (bottom_y - top_y);
float scale = x_scale < y_scale ? x_scale : y_scale;
QMatrix m = matrix();
m.scale(scale);
setMatrix(m);
}

When I test, the items which covered by Rectangle can not show center on viewport , I must srcoll the slider to show the items
and zoom fit the picture, then test again , the items will be show.

So, would you like help me ? Thanks a lot !

wysota
24th March 2009, 07:29
Use QGraphicsView::fitInView() instead of manually calculating the matrix.

aaron
24th March 2009, 08:01
Ok , I will try it . thanks!

aaron
24th March 2009, 08:37
Dear wysota,
I have solve this problem by your idea, thanks again for your help.

By the way, if you meet the same issue in your program and the current picture has been scaled, please set the second param of the QGraphicsView::fitInview(...) to Qt::KeepAspectRatio.