How to use QDomDocument to change the svg attribute?

There is a little svg file named t.svg below:

<?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 file on a QSvgWidget, and when I click the pushbutton , the text "10" should be changed to "60", but actually, I tried two ways, but both failed.

Below is the whole Qt project code.

#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?

(在Qt forum和SF发布至今未解,懒得翻译直接就贴过来了,见谅。)

阅读 1.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进