12

I want to to fit a QGraphicsScene in a QGraphicsView with different dimensions, such that it will shrink or expand according to size of view, and there should be no any scrollbar.

Javi Ortiz
  • 568
  • 1
  • 7
  • 22
anj
  • 355
  • 2
  • 5
  • 20

4 Answers4

12

This worked for me:

void MyGraphicsView::zoomToFit()
{
    fitInView(scene()->sceneRect(), Qt::KeepAspectRatio);
}

You might want to adjust the scene rectangle to have a little margin; might look better, depending on your content.

ssc
  • 9,528
  • 10
  • 64
  • 94
5

scaling the view like bellow doing what required:

view->scale(frameWidth / sceneWidth, frameHeight / sceneHeight);
Vincent Duprez
  • 3,772
  • 8
  • 36
  • 76
anj
  • 355
  • 2
  • 5
  • 20
4
view->setSceneRect(0, 0, view->frameSize().width(), view->frameSize().height());

Connect this piece of code with resizeEvent of QGraphicsView

If you set scene rect with size greater than view's, scroll bars will appear. Else if you set scene rect equal to view's frame width or less, no scroll bars will be there.

Then I guess QGraphicsView::fitInView() is your solution.

chrysante
  • 2,328
  • 4
  • 24
ScarCode
  • 3,074
  • 3
  • 19
  • 32
  • It Will just reset sceneRect, i.e. it will crop extra part which is out side of this rect, but didnt shrink it – anj Jun 06 '12 at 04:52
0

I know this doesn't answer the question, but this is at the top of google when searching for how to fit the contents to the view. It's simply:

def fit_contents(self):
    items = self.scene().items()
    rects = [item.mapToScene(item.boundingRect()).boundingRect() for item in items]
    rect = min_bounding_rect(rects)
    self.setSceneRect(rect)

Where min_bounding_rect is:

def min_bounding_rect(rectList):
if rectList == []:
    return None

minX = rectList[0].left()
minY = rectList[0].top()
maxX = rectList[0].right()
maxY = rectList[0].bottom()

for k in range(1, len(rectList)):
    minX = min(minX, rectList[k].left())
    minY = min(minY, rectList[k].top())
    maxX = max(maxX, rectList[k].right())
    maxY = max(maxY, rectList[k].bottom())

return QRectF(minX, minY, maxX-minX, maxY-minY)
MathCrackExchange
  • 595
  • 1
  • 6
  • 25