Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 627
Ticks Avatar asked Jan 30 '13 17:01

Ticks


Video Answer


2 Answers

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.

like image 135
Aziuth Avatar answered Nov 15 '22 22:11

Aziuth


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

like image 33
Gearoid Murphy Avatar answered Nov 15 '22 21:11

Gearoid Murphy