How to use QDomDocument to change the svg attribute?

发布于 2022-09-07 15:29:12 字数 2404 浏览 15 评论 0

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发布至今未解,懒得翻译直接就贴过来了,见谅。)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文