How to use the QGraphicsView's translate() function?

喜欢而已 提交于 2019-12-01 03:19:50

Center

As said Frank Osterfeld, to center your viewport at a given position, you can simply use the function centerOn.

Translate

But to translate your viewport, it exists another way that consists to change your scrollbars position :

// Your graphics view
QGraphicsView *view;

// dx, dy corresponds to your translation
int dx, dy;

// Change scrollbars position
view->horizontalScrollBar()->setValue( view->horizontalScrollBar()->value() + dx );
view->verticalScrollBar()->setValue( view->verticalScrollBar()->value() + dy );

Render

If needed, you can also hide the scrollbars :

// Hide the scrollbars
view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
Aziuth

I used the following workaround:

QTransform old_transform = transform();

QRectF scene_rect = scene()->sceneRect();
QRectF new_scene_rect(scene_rect.x()-translation.x(),
                      scene_rect.y()-translation.y(),
                      scene_rect.width(),scene_rect.height());
scene()->setSceneRect(new_scene_rect);

setTransform(old_transform);

The transform part was necessary since otherwise it resets scaling.

This solution is essentially forcing it to change where it is allowed look at, which it is far from elegant.

I hope that somebody else comes up with a clean answer that allows to actually use the translate method as intended.

Note that I use Qt 4.85, might be different with newer versions.

You need to set the transformation anchor mode of the graphics view to NoAnchor.

setTransformationAnchor(QGraphicsView::NoAnchor);

This prevents the graphics view from undoing the translation as expected by the other anchor modes (AnchorViewCenter, AnchorUnderMouse).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!