Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt 4.8.5 QGraphicsView::fitInView fails to fit exactly

Tags:

c++

qt

I Have a problem trying to fit my content (stretch) of a scene into my QDeclarativeView. I load a QML file the common way. I overrode the showEvent and resizeEvent method with the code below:

QGraphicsItem* rootItem = this->scene()->items.at(0);
QRectF rootRect = rootItem->sceneBoundingRect(); // it gives me a QRectF(0,0,1920,1080)
this->fitInView(rootRect, Qt::IgnoreAspectRatio); // Aspect doesn't matters.

The problem is that it keeps showing a little white border (almost 4 pixels) around the content. I've tested in 1920x1080, 1920x1200 and 1440x900 and all those resolutions on my desktop shows the content with the same problem. Even out of fullscreen mode it keeps the little white border.

Just to make sure it was nothing from the content, I have set the view's background brush to black and the white border became black (in other words, the content is being scaled down too much to fit in view).

Subtracting values from rectangle hardcoding is not an option once it's varying the background portion depending on the content size. (It should adapt dynamically).

Any suggestions?

like image 226
mannysz Avatar asked Jan 31 '26 10:01

mannysz


1 Answers

Just encountered the problem as well. Since the bug is not about to be solved, I'll post my partial solution. I subclassed QGraphicsView and added a method myFitInView(), that does the required scaling and centering automatically.

I guess if you need more performance you could also directly fill the the matrix, but I don't need this and therefore scale and center seperately.

Also, any previous view transformations are lost with this approach, but you could probably account for that as well, by getting the current matrix and modifying/multiplying it accordingly.

void MyGraphicsView::myFitInView(QRectF const &rect)
{
  QRectF viewRect = frameRect();

  double scaleX = viewRect.width() / rect.width();
  double scaleY = viewRect.height() / rect.height();

  QTransform trans;
  trans.scale(scaleX, scaleY);
  setTransform(trans, false);

  centerOn(rect.width() / 2, rect.height() / 2);
}
like image 144
B3ret Avatar answered Feb 02 '26 03:02

B3ret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!