This question is related to: Forcing QGraphicsItem To Stay Put
I'd like to have a QGraphicsItem
on a fixed location when moving around in the scene.
The suggested solution is to override the void paintEvent(QPaintEvent*)
of the sub-classed QGraphicsView
.
void MyGraphicsView::paintEvent(QPaintEvent*) {
QPointF scenePos = mapToScene(0,0); // map viewport's top-left corner to scene
myItem->setPos(scenePos);
}
However, the problem is that I want everything else in the scene to stay intact, i.e. if I zoom or move I want all other QGraphicsItems
to behave as default.
One poor way of solving this is to call void QGraphicsView::paintEvent(QPaintEvent*)
from within void MyGraphicsView::paintEvent(QPaintEvent*)
.
void MyGraphicsView::paintEvent(QPaintEvent* event) {
QGraphicsView::paintEvent(event);
QPointF scenePos = mapToScene(0,0); // map viewport's top-left corner to scene
myItem->setPos(scenePos);
}
However, this adds a flickering behaviour to my_item
since it's positioned first using QGraphicsView::paintEvent(event);
and then using the added code
QPointF scenePos = mapToScene(0,0); // map viewport's top-left corner to scene
myItem->setPos(scenePos);
The question is, do I have to re-implement void MyGraphicsView::paintEvent(QPaintEvent*)
from scratch and write code for both the desired behaviour of myItem
and the default behaviour of all other QGraphicsItems
, or is there an easier way to do this?
Thank you.
I think this is what you are looking for:
http://qt-project.org/doc/qt-4.8/qgraphicsitem.html#setFlag
QGraphicsItem::ItemIgnoresTransformations
Description from the docs:
You may also want to parent everything that does pan around to something else. Then, you move or scale or rotate a single graphics group to affect everything except your "un-transformable" objects.
https://qt-project.org/doc/qt-4.8/graphicsview.html#the-graphics-view-coordinate-system
https://qt-project.org/doc/qt-4.8/painting-transformations.html (a cool example, though it doesn't show this feature really)
http://qt-project.org/doc/qt-4.8/demos-chip.html (great example of using
QGraphicsView
)Hope that helps.
EDIT:
Example showing how you can achieve a static layer using parenting:
main.cpp
mygraphicsview.h
mygraphicsview.cpp