anj
anj

Reputation: 375

how to Fit QGraphicsScene in a QGraphicsView

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.

Upvotes: 14

Views: 20283

Answers (4)

ScarCode
ScarCode

Reputation: 3094

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.

Upvotes: 4

ssc
ssc

Reputation: 9913

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.

Upvotes: 12

Daniel Donnelly
Daniel Donnelly

Reputation: 617

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)

Upvotes: 0

anj
anj

Reputation: 375

scaling the view like bellow doing what required:

view->scale(frameWidth / sceneWidth, frameHeight / sceneHeight);

Upvotes: 5

Related Questions