目錄
- SVG
- QT繪制SVG流程
SVG
一般而言,QSS是無法直接使用svg圖像的。
那如何才能顯示svg呢?我們知道svg的好處有很多,如矢量圖,體積小等等
svg本來就是一個document(可參考12),QT提供了QSvgRenderer
用于訪問svg doc
QT繪制SVG流程
QSvgRenderer
讀取svg內容- 創建
QPixmap
用于容納svg圖像 - 使用
QPainter
繪制svg
PS: 注意QPixmap
設置寬高時需要考慮到DPI,否則會造成圖像錯位
對于一些控件QLabel
來說,設置setScaledContents(true)、adjustSize()、setSizePolicy(Preferred)
進行縮放
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());
SVG基本圖形繪制教程 ??
SVG 教程 ??