解释:
分析QSvgHandler的源码发现只有length(width和height属性)支持单位而不支持坐标,要理解的话,分析下面2个代码片段就够了:
// https://code.qt.io/cgit/qt/qtsvg.git/tree/src/svg/qsvghandler.cpp#n2816
static QSvgNode *createLineNode(QSvgNode *parent,
const QXmlStreamAttributes &attributes,
QSvgHandler *)
{
const QStringRef x1 = attributes.value(QLatin1String("x1"));
const QStringRef y1 = attributes.value(QLatin1String("y1"));
const QStringRef x2 = attributes.value(QLatin1String("x2"));
const QStringRef y2 = attributes.value(QLatin1String("y2"));
qreal nx1 = toDouble(x1);
qreal ny1 = toDouble(y1);
qreal nx2 = toDouble(x2);
qreal ny2 = toDouble(y2);
QLineF lineBounds(nx1, ny1, nx2, ny2);
QSvgNode *line = new QSvgLine(parent, lineBounds);
return line;
}
// https://code.qt.io/cgit/qt/qtsvg.git/tree/src/svg/qsvghandler.cpp#n3054
static QSvgNode *createRectNode(QSvgNode *parent,
const QXmlStreamAttributes &attributes,
QSvgHandler *handler)
{
const QStringRef x = attributes.value(QLatin1String("x"));
const QStringRef y = attributes.value(QLatin1String("y"));
const QStringRef width = attributes.value(QLatin1String("width"));
const QStringRef height = attributes.value(QLatin1String("height"));
const QStringRef rx = attributes.value(QLatin1String("rx"));
const QStringRef ry = attributes.value(QLatin1String("ry"));
QSvgHandler::LengthType type;
qreal nwidth = parseLength(width, type, handler);
nwidth = convertToPixels(nwidth, true, type);
qreal nheight = parseLength(height, type, handler);
nheight = convertToPixels(nheight, true, type);
qreal nrx = toDouble(rx);
qreal nry = toDouble(ry);
QRectF bounds(toDouble(x), toDouble(y),
nwidth, nheight);
//9.2 The 'rect' element clearly specifies it
// but the case might in fact be handled because
// we draw rounded rectangles differently
if (nrx > bounds.width()/2)
nrx = bounds.width()/2;
if (nry > bounds.height()/2)
nry = bounds.height()/2;
if (!rx.isEmpty() && ry.isEmpty())
nry = nrx;
else if (!ry.isEmpty() && rx.isEmpty())
nrx = nry;
//we draw rounded rect from 0...99
//svg from 0...bounds.width()/2 so we're adjusting the
//coordinates
nrx *= (100/(bounds.width()/2));
nry *= (100/(bounds.height()/2));
QSvgNode *rect = new QSvgRect(parent, bounds,
int(nrx),
int(nry));
return rect;
}
转换单位的方法parseLength()
是只在“宽度”和“高度”中使用。
解决方案:
一种解决方法是使用 QWebEngineView:
import os
import sys
from PySide2 import QtCore, QtWidgets, QtSvg, QtWebEngineWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
filename = os.path.join(CURRENT_DIR, "demo.svg")
qsvgwidget = QtSvg.QSvgWidget(filename)
qwebengineview = QtWebEngineWidgets.QWebEngineView()
qwebengineview.load(QtCore.QUrl.fromLocalFile(filename))
w = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(w)
lay.addWidget(qsvgwidget, strecth=1)
lay.addWidget(qwebengineview, strecth=1)
w.show()
sys.exit(app.exec_())