简体   繁体   中英

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"));
}

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

  • Add directly using addItem().
  • Or be the children of an item that is already on 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM