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

4

13

here i have a scene and a associated view ,then i hava a position in the scene coordinates.I want to set the center of the viewport with the position.How can i do it? I try to use the translate() function but it didn't work?

view->translate(10, 10);

The viewport should move with the delta x 10, and delta y 10, but it didn't work!

Assiniboine answered 30/1, 2013 at 17:56 Comment(2)
Use QGraphicsView::centerOn for centering. What exactly didn't work about translate? What's the current viewport position and the dimensions of your scene (sceneRect())?Masterstroke
I'm seeing this same thing. I can set a translated QTransform or I can use QGraphicsView::translate() and nothing happens. Kind of frustrating.Sn
A
6

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).

Alkalize answered 27/4, 2019 at 22:54 Comment(0)
J
3

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 );
Jaco answered 31/7, 2017 at 13:11 Comment(0)
M
2

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.

Machmeter answered 29/3, 2018 at 12:1 Comment(0)
M
0

See the Bug Report, along with work around.

Melodrama answered 21/9, 2013 at 18:21 Comment(1)
It's helpful to summarize the conclusion drawn from the link in your answer.Gauger

© 2022 - 2024 — McMap. All rights reserved.