Important: Please read the Qt Code of Conduct -

How to resize svg image in QGraphicsView?

  • Hi, I am trying to resize a svg image inside QGraphicsView, by using Pyside2.QtSvg.QGraphicsSvgItem.
    But I came cross some problems when resizing it.

    For example, I have a tiny QRectF with w=0.1 and h=0.1.
    and I want to put a large svg image inside this QRectF.

    I used QGraphicsSvgItem.setScale() to fit the svg into the view,
    but the boundingRect of svg Item was still original size.

    Here is the sample code:

    app = QtWidgets.QApplication()
    rect = QtWidgets.QGraphicsRectItem(0.02, 0, 0.1, 0.1)
    pen = rect.pen()
    svg = QtSvg.QGraphicsSvgItem(":/submarine.svg")
    # Make the size of svg image fit the size of rect
    # This won't change the boundingRect.
    svg.setScale(0.1 / 427)
    label = QtWidgets.QLabel()
    # To show the size of boundingRect
    label.setText("Bounding Rect of svg:\n[{},{},{},{}]".format(
        svg.boundingRect().x(), svg.boundingRect().y(),
        svg.boundingRect().width(), svg.boundingRect().height()
    scene = QGraphicsScene()
    view = QGraphicsView()
    # Scale the view to enlarge tiny items. 
    # This won't change the boundingRect of items.
    view.scale(1000, 1000) 
    widget = QtWidgets.QWidget()
    layout = QtWidgets.QHBoxLayout()
    layout.addWidget(view, stretch=5)

    Here is the program result: The boundingRect I expected to be [0,0,0.1,0.1] here.

    Svg image source: Icons made by DinosoftLabs from Flaticon

    It shows that the boundinRect won't change no matter I scale the item or scale the view, although we can see in the view the svg is inside the tiny rect.
    But this will cause problem in collision detection, because the boundingRect of svg Image is larger than what I have expected it to be.

    So I want to know that is there any way able to change the view size of svg and also the boundingRect?
    I cannot find functions such as setSize(), setWidth(), setHeight() in QGraphicsSvgItem class

    Thanks for any help!

  • I think I figure it out. It's because different coordinate system.

    The item.boundingRect() returns the rect in item coordinate, which will always be the size of item itself.
    On the other hand, the collision detection uses the scene coordinate. There are transformations between the two coordinate system.

    so I should do like this:

     rect = item.mapToScene(item.boundingRect())
     collisionDetection(rect, otherRect)

    Thanks for the qt document! :)

Log in to reply