当前位置: 首页> 教育> 高考 > 【QT】Svg图标

【QT】Svg图标

时间:2025/7/11 23:40:03来源:https://blog.csdn.net/weixin_44623642/article/details/139845369 浏览次数:0次

SVG

一般而言,QSS是无法直接使用svg图像的。
那如何才能显示svg呢?我们知道svg的好处有很多,如矢量图,体积小等等
svg本来就是一个document(可参考12),QT提供了QSvgRenderer用于访问svg doc

QT绘制SVG流程

  1. QSvgRenderer读取svg内容
  2. 创建QPixmap用于容纳svg图像
  3. 使用QPainter绘制svg

PS: 注意QPixmap设置宽高时需要考虑到DPI,否则会造成图像错位

e.g.

// .h
#ifndef __SVGICON_H__
#define __SVGICON_H__#include "DeviceDiagUI_Global.h"	// 导出宏
#include <QDomDocument>class QString;
class QPixmap;class DEVICEDIAGUI_EXPOT SvgIcon
{
public:explicit SvgIcon(const QString& _svgPath);void setSVGProperty(const QDomElement& elem, const QString& _tagName,const QString& _property, const QString& _value);QString getSVGProperty(const QString& _tagName, const QString& _property);/// @brief 获取xml文本const QDomDocument getDomDocument();/// @brief 获取xml图像const QPixmap* pixmap();
private:QDomDocument svgDoc_ = QDomDocument();QPixmap* pixmap_ = nullptr;
};#endif // !__SVGICON_H__
#include "SvgIcon.h"#include <QtSvg/QSvgRenderer>
#include <QtCore/QFile>
#include <QPixmap>
#include <QPainter>
#include <QIcon>
#include <QGuiApplication>
#include <QScreen>SvgIcon::SvgIcon(const QString& _svgPath)
{QFile tFile(_svgPath);tFile.open(QIODevice::ReadOnly);QByteArray tData = tFile.readAll();tFile.close();svgDoc_.setContent(tData);auto tDpi = QGuiApplication::primaryScreen()->logicalDotsPerInch();QSvgRenderer* tSvgRender = new QSvgRenderer(_svgPath);pixmap_ = new QPixmap(getSVGProperty("svg", "width").toInt() * tDpi, getSVGProperty("svg", "height").toInt() * tDpi);pixmap_->fill(Qt::transparent);QPainter tPainter(pixmap_);tSvgRender->render(&tPainter);
}void SvgIcon::setSVGProperty(const QDomElement& elem, const QString& _tagName, const QString& _property, const QString& _value)
{if (elem.tagName().compare(_tagName) == 0){const_cast<QDomElement*>(&elem)->setAttribute(_property, _value);for (int i = 0; i < elem.childNodes().count(); i++){if (!elem.childNodes().at(i).isElement()){continue;}setSVGProperty(elem.childNodes().at(i).toElement(), _tagName, _property, _value);}}
}QString SvgIcon::getSVGProperty(const QString& _tagName, const QString& _property)
{const auto& elem = svgDoc_.documentElement();if (elem.tagName().compare(_tagName) == 0){return const_cast<QDomElement*>(&elem)->attribute(_property);}return QString::number(36);
}const QDomDocument SvgIcon::getDomDocument()
{return svgDoc_;
}const QPixmap* SvgIcon::pixmap()
{return pixmap_;
}

使用

SvgIcon* closeIcon = new SvgIcon(":/Resource/Icon/closeBtn.svg");
QToolButton* closeButton = new QToolButton;
closeButton->setIcon(*closeIcon->pixmap());

  1. SVG基本图形绘制教程 ↩︎

  2. SVG 教程 ↩︎

关键字:【QT】Svg图标

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: