qtqgraphicspixmapitem

QGraphicsPixmapItem doesn't show in QGraphicsScene


In the inherited class GraphicWidgetItem from QGraphicsItem, I create rectangles, a circle, and a picture. Everything is displayed except the picture. What am I doing wrong?

CustomItem::CustomItem( QObject *parent):
   GraphicWidgetItem(parent)
{
    QGraphicsRectItem *topLevel = new QGraphicsRectItem(this);
    topLevel->setRect(0, 0, 20, 20);
    topLevel->setBrush(Qt::gray);
    topLevel->setPos(-30 , -30);

    QGraphicsRectItem *lowLevel = new QGraphicsRectItem(this);
    lowLevel->setRect(0, 0, 20, 20);
    lowLevel->setBrush(Qt::red);
    lowLevel->setPos(-30 , 60);

     QGraphicsEllipseItem *circle = new QGraphicsEllipseItem(this);
     circle->setBrush(Qt::green);
     circle->setRect(0, 0, 20, 20);

    QGraphicsPixmapItem* pi =  new QGraphicsPixmapItem(QPixmap(":/icons/image"));
}

Solution

  • There is only 2 way for an item to appear in the scene:

    In your case "rectangles" and "circles" are shown because they are children of CustomItem but "pi" is not so it fails, the solution is to pass to "this" as parent:

    QGraphicsPixmapItem* pi =  new QGraphicsPixmapItem(QPixmap(":/icons/image"), this);
    

    Or

    QGraphicsPixmapItem* pi =  new QGraphicsPixmapItem(QPixmap(":/icons/image"));
    pi->setParent(this);