Duilib添加style全局样式简化布局的书写

来源:赵克立博客 分类: C/C++ 标签:duilib发布时间:2017-10-26 10:26:40最后更新:2017-10-26 10:54:06浏览:2187
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-10-26 10:54:06
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

使用官方duilib时发现只有全局默认样式的书写<Default name="Button" value="" /> 可以把某一类的控件样式统一设置一下,不能设置单独的把一段样式应用到哪个控件上,一些第三方维护的duilib都实现啦这样的功能定义一个<Style name="btn_default" value="" />然后哪个控件需要啦就定义一个 style="btn_default"  属性就可以使用定义好的样式,下面就实现一下并且可以用空格分隔开使用多个样式,类似css选择器一样,实现方法可以仿照Default的实现方法,

首先,在UIDlgBuilder.cpp中找到解析Default的代码处,查找 _tcsicmp(pstrClass, _T("Default")) == 0,能找到两处地方分别仿照代码添加上Style的解析过滤,

第一处代码添加上,代码比较少直接就贴修改好的啦

image.png

第二处修改添加代码

else if (_tcsicmp(pstrClass, _T("Style")) == 0) {
    nAttributes = node.GetAttributeCount();
    LPCTSTR pControlName = NULL;
    LPCTSTR pControlValue = NULL;
    bool shared = false;
    for (int i = 0; i < nAttributes; i++) {
        pstrName = node.GetAttributeName(i);
        pstrValue = node.GetAttributeValue(i);
        if (_tcsicmp(pstrName, _T("name")) == 0) {
            pControlName = pstrValue;
        }
        else if (_tcsicmp(pstrName, _T("value")) == 0) {
            pControlValue = pstrValue;
        }
        else if (_tcsicmp(pstrName, _T("shared")) == 0) {
            shared = (_tcsicmp(pstrValue, _T("true")) == 0);
        }
    }
    if (pControlName) {
        pManager->AddDefaultAttributeList(pControlName, pControlValue, shared);
    }
}

如图所示添加到下面

image.png

最后在每个控件解析自己的属性时判断下如果是style属性就就解析一下就可以啦,注意这里的style用小写,上面的都是大写,查找  pControl->SetAttribute(attribute_name, node.GetAttributeValue(i));  把这样地方的代码替换成下面的

for( int i = 0; i < nAttributes; i++ ) {
    //这个是原来代码pControl->SetAttribute(node.GetAttributeName(i), node.GetAttributeValue(i));
    //这里是自定义代码
    const CDuiString attribute_name = node.GetAttributeName(i);
    //这里为啦跟原来的属性一致用标签属性都用小写字母
    if (attribute_name == _T("style"))
    {
        LPCTSTR str= node.GetAttributeValue(i);
        const char * split = " ";
        char * p;
        p = strtok((char*)str, split);
        while (p != NULL) {
            LPCTSTR pDefaultAttributes = pManager->GetDefaultAttributeList(p);
            if (pDefaultAttributes)
            {
                pControl->SetAttributeList(pDefaultAttributes);
            }
            p = strtok(NULL, split);
        }
    }
    else
    {
        pControl->SetAttribute(attribute_name, node.GetAttributeValue(i));
    }
    //自定义代码结束
}

使用方法

<Style name="btn_default" value="bordersize=&quot;1&quot; bordercolor=&quot;#cccccc&quot; textcolor=&quot;#FFFFFFFF&quot; bkcolor=&quot;#FF1AAD19&quot; hotbkcolor=&quot;#ff129611&quot; pushedbkcolor=&quot;#ff1AAD19&quot; font=&quot;1&quot;  padding=&quot;0,5,0,5&quot;" />
<Style name="btn_default2" value="bordersize=&quot;10&quot;" />
<Button style="btn_default btn_default2" name="btn_sendrequest" width="80" text="发送请求" />

button会使用btn_default btn_default2两个样式并且后面的会覆盖前面的,


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python