Qt控件上设置图片/png,svg

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值