Search code examples
c++qtqgraphicsview

Overlaying image within larger image using QGraphicsView or QGraphicsScene


I'm new to Qt, so I might mangle this question. Having said that-

I'm rendering an image within a subclassed QGraphicsView. I added the image to the scene as a Pixmap with addPixmap(). I'd like to overlay (blit) smaller images on top of the larger one in specific locations. I can add the smaller image to the scene as well by again calling addPixmap(), but it always displays in the upper left corner. I'd like to set those coordinates myself.

How can I accomplish this?

Thanks!


Solution

  • QGraphicsScene::addPixmap returns a pointer to the added QGraphicsPixmapItem. If you want to set its position, you can do something like this:

    QGraphicsPixmapItem *item = scene->addPixmap(yourPixmap);
    item->setPos(50, 50); // sets position to scene coordinate (50, 50)
    

    If you want to overlay images on top of other images, make sure you know about z-values. See the QGraphicsItem documentation for details. Basically, the z-value determines the stacking order.

    Lastly, familiarize yourself with parenting of QGraphicsItems. When a QGraphicsItem has a parent item, it means (among other things) that its coordinates are expressed in terms of its parents' coordinates. So if an item has a position of (0, 0), but it's the child of an item whose scene position is (50, 50), then the child item will be displayed at (50, 50). So, given the above example, you could then do:

    QGraphicsPixmapItem *childItem = new QGraphicsPixmapItem(item);
    

    This creates a new item, "childItem", whose parent is "item". Its coordinates are (0, 0), because they haven't been set yet, but its scene coordinates are (50, 50), because it is the child of "item". Note that when you specify an item's parent, you don't need to add the child item to the scene; it is implicitly added.