首页 > 技术知识 > 正文

Qt 控件图标SVG实现

应用程序开发时为了美观通常都会有几套皮肤,界面背景颜色、文字颜色等是可以调整rgb值切换成对应皮肤的颜色值,但是图标就不可以这样切换,除非提前加载所有皮肤的图标,但是这样就会加载很多份,浪费程序资源,这个时候我们就可以使用svg格式的图片,这样就可以动态修改图片颜色。

首先来讲一下是如何动态修改SVG的颜色的,使用文本文档打开SVG其实可以发现SVG就是xml格式的文件,所以我们可以通过修改节点属性修改图片的颜色。

加载SVG图标 //定义按钮 QToolButton *btn= new QToolButton ; 加载SVG文件 svg_path:文件路径 QSvgRenderer *svg_render = new QSvgRenderer(svg_path); SVG转换QPixmap 定义QPixmap 对象 QPixmap *pixmap = new QPixmap(32, 32); pixmap->fill(Qt::transparent); //创建QPixmap 画布 QPainter painter(pixmap); //将SVG图片写到画布中去 svg_render->render(&painter); 创建图标 QIcon ico(*pixmap); //按钮设置图标 btn->setIcon(ico); 以上几行代码就是qt中显示SVG图片的方法,接下来要修改SVG图片,将svg文件读到xml对象中,然后修改颜色属性 QString path = svg_path; //创建文件对象 QFile file(path); //只读模式打开文件 file.open(QIODevice::ReadOnly); //将文件读到data缓存中 QByteArray data = file.readAll(); //创建QDomDocument 对象 QDomDocument doc; //将读出来的SVG数据写到QDomDocument 对象中 doc.setContent(data); QString color = “#ff0000”;
<
//修改颜色 SetSVGColor(doc.documentElement(), “path”, “fill”, color); void SetSVGColor(QDomElement &elem, QString strtagname, QString strattr, QString strattrval) { if (elem.tagName().compare(strtagname) == 0)//查找节点 { QString before_color = elem.attribute(strattr); //修改属性 const_cast<QDomElement *>(&elem)->setAttribute(strattr, strattrval); QString color = elem.attribute(strattr); } for (int i = 0; i < elem.childNodes().count(); i++) { if (!elem.childNodes().at(i).isElement()) { continue; } SetSVGColor(elem.childNodes().at(i).toElement(), strtagname, strattr, strattrval); } }

下面给出一段SVG数据,复制粘贴保存.svg格式就可以了

<svg xmlns=”http://www.w3.org/2000/svg” version=”1.1″> <path th d=”M250 150 L150 350 L350 350 Z” fill=”#00ff00″ /> </svg>

猜你喜欢