1
votes

I have a QGraphicsScene and a QGraphicsView that displays it. I need to add a QGraphicsItem to the scene and keep it at the same position even when I scroll the view. I tried overriding view's scrollContentsBy() method as follows but it didn't do the trick.

void FETimelineView::scrollContentsBy( int dx, int dy )
{
    QGraphicsView::scrollContentsBy(dx, dy);

    QRectF oRect = p_CatBar->rect();
    p_CatBar->setPos( oRect.x() + dx, oRect.y() + dy );
}

Btw, FETimelineView is my QGraphicsView and p_CatBar is of type QGraphicsItem. Please help, thanks in advance.

2

2 Answers

3
votes

Rather than moving it by the scrolled amount, You can get the position that you want it to be relative to the view and then set it directly according to that. So it would be something like this: -

// Assuming that the Graphics Item top left needs to be at 50,50 
// and has a width and height of 30,20

void FETimelineView::scrollContentsBy( int dx, int dy )
{
    QGraphicsView::scrollContentsBy(dx, dy);

    // get the item's view position in scene coordinates
    QRect scenePos = mapToScene(QRect(50, 50, 30, 20));
    p_CatBar->setPos(scenePos);
} 
1
votes

I think the easier way it's actually the inverse of what you ask: try setting the flag ItemIgnoresTransformations in QGraphicsItem::GraphicsItemFlags.

There are other flags that could help you, see the docs.