Advanced SVG image usage in QML



  • Hi all,

    I know I can display SVG image using QImage item in QML but I'm trying to display SVG image with multiple SVG elements and attach to some of them mouse events.
    I thought using QGraphicSvgItem class will be enough for me and done some example code:

    class SVGImage : public QQuickPaintedItem
    
    void SVGImage::paint(QPainter *painter)
    {
        qDebug() << "SVGImage::paint";
        QGraphicsSvgItem svgItem{QLatin1String("img.svg")};
        svgItem.setElementId("svg_34");
        svgItem.renderer()->render(painter);
    }
    

    and the image is being painted but it looks like whatever I'll set up into svgItem it will be ignored - whole image is being painted.
    I'm rather newbie in Qt's painting stuff, there is a lot of options and dependencies so to make it a little bit shorter I need some tips which classes should I learn to do this correctly.

    All I need is to create C++ implementation for QML object which will paint SVG image and to each SVG item it will attach mouse event (separately so I'll be able to find out which item has been clicked) and manage to handle this event correctly.

    Or maybe there is any public interface which is responsible for parsing SVG file? I've found some internal implementations but due to further problems with fixing issues triggered by changes in internal API I'm rather far from using it.

    Thanks in advance!


  • Moderators

    @osmial
    QGraphics* classes are actually part of the graphics view framework and shouldn't be used outside of a QGraphicsView/QGraphicsScene.

    You should rather use QSvgRenderer instead.
    But when i undertsand you correctly you want interaction for each element inside a SVG file? I am not aware of such a suffisticated class in Qt.
    You could parse the SVG file for the elements using Qt's xml classes and add them separatley.

    Or i guess it's probably even better to write a custom class/widget which parses the SVG and caches it's element properties and process the mouse events accordingly. Handle the repaints on every change and write out a valid svg after the changes.



  • Thanks @raven-worx for your response.
    I've already used QSvgRenderer but was looking for more functionalities so thought I should use QGraphicsSvgItem cause in Qt's documentation it is listed next to QSvgRenderer class...

    I thought there is some SVG parser provided as a public API (i.e. QImage objects are being parsed and displayed somehow), but it looks like I'll need to use XML parser and code some stuff.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.