You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt6加载SVG时百分比尺寸元素显示异常问题

Ah, I see the issue here! The problem is that your PyQt6 code isn't explicitly telling the scene or view to respect the SVG's intrinsic dimensions, so the percentage-based rectangle falls back to a default 100x100 viewport instead of using the SVG's defined 400x400 size.

Here's how to fix it:

We need to get the SVG's native size from the renderer, then adjust the scene and view to match that size. This ensures percentage-based elements scale correctly to the SVG's actual dimensions.

Corrected Code

from PyQt6.QtWidgets import QWidget, QVBoxLayout, QGraphicsView, QGraphicsScene, QApplication
from PyQt6.QtSvgWidgets import QGraphicsSvgItem
from PyQt6.QtSvg import QSvgRenderer
from PyQt6 import QtCore  # Add this for aspect ratio control
import sys

class PlotPanel(QWidget):
    def __init__(self, svgpath, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        layout.addWidget(self.view)
        
        data = open(svgpath).read()
        self.renderer = QSvgRenderer(bytes(data, "UTF-8"))
        
        # Get the SVG's intrinsic size from the renderer
        svg_size = self.renderer.defaultSize()
        # Set the scene dimensions to match the SVG's native size
        self.scene.setSceneRect(0, 0, svg_size.width(), svg_size.height())
        
        self.svg = QGraphicsSvgItem()
        self.svg.setSharedRenderer(self.renderer)
        self.scene.addItem(self.svg)
        
        # Ensure the view displays the entire SVG while keeping aspect ratio
        self.view.fitInView(self.scene.sceneRect(), QtCore.Qt.AspectRatioMode.KeepAspectRatio)

app = QApplication(sys.argv)
svgpath = sys.argv[1]
window = PlotPanel(svgpath)
window.show()
app.exec()

Key Changes Explained

  • Added QtCore import: Lets us use aspect ratio controls to avoid distorting the SVG.
  • Fetched SVG intrinsic size: renderer.defaultSize() pulls the exact width/height defined in your SVG (400x400 here).
  • Set scene rect: This tells the graphics scene to use the SVG's actual dimensions, so your 100% width/height rectangle references the correct 400x400 space instead of a default 100x100 viewport.
  • Fit view to scene: fitInView ensures the entire SVG is visible in the window without clipping, while maintaining the original aspect ratio.

This fix preserves your SVG's percentage-based sizing, so you don't have to hardcode pixel values into the SVG file itself.

内容的提问来源于stack exchange,提问作者Spacedman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 06:39:51