【发布时间】:2015-08-18 09:07:17
【问题描述】:
我需要使用 QGraphicsSvgItem sublcas 来处理 svg 对象。
我正在学习 svg - 我注意到,如果 svg 的根元素是 <svg ..>,则 svg 显示良好
然而,在使用 w3schools 示例时,我注意到他们所有的示例都嵌入在 html 中,并且我的代码可能必须同时处理这两种类型(简单的 svg,以及包含 svg 的 html)。
所以,我看到的解决方案是,提取 svg 元素(及其所有子元素)并用它替换根元素。
在我看来,代码很清楚:
QDomDocument _svgXML;
void setContentFromFile(QString filename)
{
QFile file(filename);
file.open(QFile::ReadOnly | QFile::Text);
QTextStream in(&file);
QString data = in.readAll();
file.close();
_svgXML.setContent(svgContent);
checkRoot();
}
void checkRoot()
{
QDomElement rootElem = _svgXML.documentElement();
recursivelyCheckRoot(rootElem);
qDebug(qPrintable(QString("root ") + rootElem.nodeName()));
// or
qDebug(_svgXML.toByteArray());
}
void recursivelyCheckRoot(QDomElement& rootElem)
{
if(rootElem.nodeName() == "svg")
return;
QDomNode n = rootElem.firstChild();
while(!n.isNull())
{
if(n.isElement())
{
QDomElement e = n.toElement();
if(e.nodeName() == "svg")
{
rootElem = e; return;
}
recursivelyCheckRoot(e);
}
n = n.nextSibling();
}
}
唯一的问题是它不起作用。我看没有变化。
请帮我提取 svg 元素并使其成为根...丢弃所有其他内容。
示例来源:
<!DOCTYPE html>
<html>
<body>
<svg width="400" height="150">
<defs>
<linearGradient id="grad1" y1="0%" x1="0%" y2="0%" x2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1"/>
</linearGradient>
</defs>
<ellipse fill="url(#grad1)" cx="200" cy="70" rx="85" ry="55"/>
<text x="150" y="86" fill="green" font-family="Verdana" font-size="45">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>
想要的结果:
<svg width="400" height="150">
<defs>
<linearGradient id="grad1" y1="0%" x1="0%" y2="0%" x2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1"/>
</linearGradient>
</defs>
<ellipse fill="url(#grad1)" cx="200" cy="70" rx="85" ry="55"/>
<text x="150" y="86" fill="green" font-family="Verdana" font-size="45">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>
(!DOCTYPE 或任何其他声明可以保留)
【问题讨论】:
-
我不确定这是否可行。曾经是 html 文档,我认为始终是 html 文档。
-
@RobertLongson LOL :)))) ..... 然而应该可以从文档中提取一个节点及其所有子节点