Qt 控件图标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(&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);
}
}