How to use QDomDocument to change the svg attribute?
Solved
General and Desktop
-
A little svg file:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <text id="HW" x="50" y="50" fill="blue" stroke="none" font-family="Microsoft YaHei" font-size="16">10</text> </svg>
Now, I want to show the svg on a QSvgWidget, and change the text to "60", and repaint the QSvgWidget to show the text "60", but I failed.
#ifndef SVG_WIDGET_H #define SVG_WIDGET_H #include <QWidget> #include <QtSvg> #include <QVBoxLayout> #include <QPushButton> #include <QDomDocument> class SVGWidget : public QWidget { Q_OBJECT public: SVGWidget(QWidget* parent = 0) : QWidget(parent) { m_btn = new QPushButton("Change"); connect(m_btn, SIGNAL(clicked(bool)), this, SLOT(change())); QFile file(":/t.svg"); file.open(QFile::ReadOnly | QFile::Text); m_domDoc.setContent(&file); file.close(); m_svgWidget = new QSvgWidget; m_svgWidget->load(m_domDoc.toByteArray()); QVBoxLayout* vLayout = new QVBoxLayout(this); vLayout->addWidget(m_btn); vLayout->addWidget(m_svgWidget); this->setFixedSize(800, 480); } ~SVGWidget() { } public slots: void change() { // change the value, I used two ways to try it, but both failed. QDomNodeList domNodeList1 = m_domDoc.elementsByTagName("text"); // way 1 QDomText domText = domNodeList1.at(0).toText(); domText.setNodeValue("60"); qDebug() << "way 1" << domText.nodeValue(); // way 2 QDomNode domNode = domNodeList1.at(0); domNode.setNodeValue("60"); qDebug() << "way 2" << domNode.nodeValue(); // repaint the widget m_svgWidget->load(m_domDoc.toByteArray()); } private: QSvgWidget* m_svgWidget; QPushButton* m_btn; QDomDocument m_domDoc; }; #endif // SVG_WIDGET_H
Can someone give me some advice?
-
Hi
text tag is inside svg tag and the 10 text is actually inside a text element.void change() { QDomElement root = m_domDoc.firstChildElement(); qDebug() << "root=" << root.tagName(); QDomNodeList text = root.elementsByTagName("text"); if (text.size() && text.at(0).isElement() ) { QDomElement elem = text.at(0).toElement(); qDebug() << "text value " << elem.nodeValue(); qDebug() << " text child" << elem.childNodes().at(0).nodeValue() << "type " << elem.childNodes().at(0).nodeName() ; elem.childNodes().at(0).setNodeValue("60"); // change it }
output
root= "svg"
text value ""
text child "10" type "#text"