c++qtqgraphicsviewqtguiqtsvg

How to open svg file in QT (QGraphicsView)


How to open svg file like png file. For example it works for png file:

scene=new QGraphicsScene(QRect(10, 10, 680, 520));  
view=new QGraphicsView(this);
image=new QGraphicsPixmapItem(QPixmap("example.png"));

scene ->addItem(image);   
view ->setScene(scene);   
view ->setGeometry(QRect(270, 35, 700, 540));

Any ideas?


Solution

  • As per my comment, you could use QGraphicsSvgItem as per documentation:

    QGraphicsSvgItem::QGraphicsSvgItem(const QString & fileName, QGraphicsItem * parent = 0)

    Constructs a new item with the given parent and loads the contents of the SVG file with the specified fileName.

    So, you would basically write something as follows:

     QGraphicsSvgItem *item = new QGraphicsSvgItem("example.svg");
    

    You can also follow th example in the documentation if you wish to use it with the QSvgRenderer.

    QSvgRenderer *renderer = new QSvgRenderer(QStringLiteral("example.svg"));
    QGraphicsSvgItem *item = new QGraphicsSvgItem();
    
    item->setSharedRenderer(renderer);
    item->setElementId(QStringLiteral("example"));
    

    Here you can even find a more sophisticated example of doing this:

    SVG Viewer Example