3

How would I go about adding an interactive SVG file to a QGraphicsScene? I can add an interactive SVG file, but it's just displayed as a static image. I was reading about QGraphicsWebView but can't figure out how add SVG files to it and examples are lacking.

Let me be a little more specific with what I'm looking for. Let's say I have a SVG file that draws a box. When I mouse over that box I want to color to change triggered off a hover event. Do I have to edit the file and redraw the image? Feels like there should be a way of doing interactive SVG files with Qt.

Jeff
  • 6,932
  • 7
  • 42
  • 72

2 Answers2

5

I had the same problem and your question pointed me in right direction (using QGraphicsWebView()). Solution is actually very simple:

import sys
from PyQt4 import QtCore, QtGui, QtSvg
from PyQt4.QtWebKit import QGraphicsWebView
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    scene = QtGui.QGraphicsScene()
    view = QtGui.QGraphicsView(scene)

    br = QtSvg.QGraphicsSvgItem("C:\your_interactive_svg.svg").boundingRect()

    webview = QGraphicsWebView()
    webview.load(QtCore.QUrl("C:\your_interactive_svg.svg"))
    webview.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
    webview.setCacheMode(QtGui.QGraphicsItem.NoCache)
    webview.resize(br.width(), br.height())

    scene.addItem(webview)
    view.resize(br.width()+10, br.height()+10)
    view.show()
    sys.exit(app.exec_())

It works perfect for me (scripting and other stuff).

As you can see, I've also loaded my svg as QGraphicsSvgItem, because I didn't know other way to get size of my svg.

Aleksandar
  • 3,541
  • 4
  • 34
  • 57
2

I figured out a way, but I don't think it's the best way. I have two files: white.svg green.svg

in the hover functions I render the image and force show it.

def hoverEnterEvent(self, event):
    self.render.load('green.svg')
    self.show()

def hoverLeaveEvent(self, event):
    self.render.load('white.svg')
    self.show()

where self is a QGraphicsSvgItem

I don't like this way because I now have to have two .svg files insted of one. If anyone has a better solution, I'm open to suggestions.

Jeff
  • 6,932
  • 7
  • 42
  • 72