Important: Please read the Qt Code of Conduct -

SVG file in QGraphicsView

  • Hi, I'm wondering if I can put an SVG file into a QGraphicsView widget. I've seen something about QSvgRenderer, but I don't know if that would work.
    I was using QPixmap when I was displaying jpg files, but svg files don't work.

  • Lifetime Qt Champion


    QGraphicsSvgItem is what you are looking for.

  • Hi @SGaist, ok, but I don't know how to properly use it. I did this:

    QGraphicsSvgItem svg(":/hands/handLeftDark.svg");

    But I don't know how to add in in QGraphicsView now. I tried:


    But I don't know how to convert QGraphicsSvgItem to QGraphicsItem.

  • Lifetime Qt Champion

    QGraphicsSvgItem *svgItem = new QGraphicsSvgItem(":/hands/handLeftDark.svg");

  • @SGaist I'm getting an error:

    undefined reference to `QGraphicsSvgItem::QGraphicsSvgItem(QString const&, QGraphicsItem*)'

  • Lifetime Qt Champion

    Are you linking the svg module ?

  • in pro
    QT += svg
    in cmake
    find_package(Qt5 REQUIRED ... Svg ... )

  • Hi @JoeCFD, I added svg in .pro file, but I don't know is in cmake

  • @Sucharek that may be good enough for you after you put it into pro file. I use both.

  • Hi @JoeCFD, ok I just realised that I put it in a wrong thing in my .pro file, and when I put it right, it works. I don't know where the cmake file is, but it doesn't matter not because it works.
    But I have another problem, you see, I have a dark and light mode in my app, and when I switch, QGraphicsView makes 2 lines on the edges of the image. I tried "ui->graphicsview->scene()->clear", but that just crashes the application. This is how the lines look:

  • override this one and define the size of your pic
    QRectF boundingRect() const

  • @JoeCFD, ok I tried that, but it doesn't seem to be working...
    It doesn't display anything. Here's what it displays: 93648bc8-6ccf-491a-95f2-73cbca12e548-image.png
    My code:

    QPixmap left(":/hands/handLeftDark.svg");
    QRectF size(150, 150, 150, 150);

  • Hi, so I solved it by doing "ui->graphicsView_LeftHand->scene()->removeItem(svgLeftDark);" and then adding the other svg.
    So it's like this:

    QGraphicsScene *sceneLeft = new QGraphicsScene(this);
    QGraphicsSvgItem *add = new QGraphicsSvgItem("path/to/svg.svg");
    QGraphicsSvgItem *remove = new QGraphicsSvgItem("path/to/svg.svg");
    ui->graphicsView_LeftHand->scene()->removeItem(remove); //remove the svg that you don't want
    ui->graphicsView_LeftHand->scene()->addItem(add); //add the svg that you want

    If you want to have it across different voids, just add this at the top of the .cpp file (where you declare cross void variables, ...):

    QGraphicsSvgItem *add = new QGraphicsSvgItem("path/to/svg.svg");
    QGraphicsSvgItem *remove = new QGraphicsSvgItem("path/to/svg.svg");

Log in to reply