PDA

View Full Version : Adjusting window to QGraphicsView contents



IrYoKu
27th August 2007, 12:41
In my application, I open a QMainWindow that has a QGraphicsView in order to display an image, but I have a problem as I would like to resize the QMainWindow to the size of the image displayed by the QGraphicsView. Can someone give me some guidelines about the way of doing it?

aMan
27th August 2007, 13:01
I think that what you need is http://doc.trolltech.com/4.3/qabstractscrollarea.html#maximumViewportSize (just set the size of the main window to this+bars etc). I'm not sure, so just give it a try..

Bitto
27th August 2007, 13:10
Do you want a once-only resize, or do you want the window to stay fixed at this new size? That is, do you want the user to be able to resize the window after your resize?

Most of the time, when you want the viewport to assume a size you can rely on QGraphicsView's sizeHint(), which will default to the size of the scene. Otherwise, you can easily determine the size (bounding rect) of any item on the scene by going



void CustomView::keyPressEvent(QKeyEvent *event)
{
// whenever someone hits a key, resize the view to an item's size.
QRect itemRect = mapFromScene(pixmap->boundingRect()).boundingRect().toRect();
resize(itemRect.size() + QSize(frameWidth() * 2, frameWidth() * 2);
}


The pixmap boundingrect is a bit larger than the pixmap itself; depending on how you display the pixmap you could map just a QRectF(QPointF(), pixmapSize) instead.

You can also go the opposite way; call QGraphicsView::fitInView() to make the item fit inside the view without actually resizing the view. Keep in mind that this approach uses transformations, though, slow on X11.