Qt Snippet: QGraphicsView fitInView() and the unwanted margins bug

In case you are working with Qt Graphics View Framework you probably make use of the QGraphicsView method fitInView(). This function, based to the official documentation, scales the view matrix and scrolls the scroll bars to ensure that the scene rectangle rect fits inside the viewport. 


Unfortunately it seem that, until Qt version 5.5, this function have a strange bug that doesn't resize correctly the scene and add an unwanted margin of some pixels in all sides. This will have as practical result that each graphics item you want to position on scene sides will not correctly be aligned with sides itself but will appear moved on the center of some pixels (the margin added). The common use of this function is in addition of QGraphicsView resize event as follow:

void MyGraphicsView::resizeEvent(QResizeEvent *event)
{
    fitInView(sceneRect());

    QGraphicsView::resizeEvent(event);
}

Googling around it seem the only solution would be to recalculate "manually" the matrix based to the new size as follow:

void MyGraphicsView::resizeEvent(QResizeEvent *event)
{
    QTransform Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
    Matrix.scale(width() / sceneRect().width(), height() / sceneRect().height());
    setTransform(Matrix);

    QGraphicsView::resizeEvent(event);
}

This code is working as expected and resize the scene to fit exactly the viewport. Looking back it seem this bug is present from around Qt version 4.8 and is very strange it has not been fixed yet...

Comments

Popular posts from this blog

Access GPIO from Linux user space

Launch an app from Android shell terminal