Qt4 style sheet 自定义属性选择器selector

来源:互联网 发布:序列号管理网站源码 编辑:程序博客网 时间:2024/05/16 08:35

 

Qt4 style sheet 自定义属性选择器selector

from http://hi.baidu.com/virusfun/blog/item/f834b3dc77f2ce4694ee3793.html
by virusfun

现在项目的GUI里style设置基本都通过stylesheet来做的,里面有几个比较好用的记下来。

在Qt帮助文档里,stylesheet的语法里有通过selector来设置style的方法,其中有两个有意思的是:




Property SelectorQPushButton[flat="false"]Matches instances of QPushButton  that are not flat . You may use this selector to test for any Qt property  that supports QVariant::toString () (see the toString() function documentation for details). In addition, the special class  property is supported, for the name of the class.

This selector may also be used to test dynamic properties. For more information on customization using dynamic properties, refer to Customizing Using Dynamic Properties .

Instead of = , you can also use ~=  to test whether a Qt property of type QStringList  contains a given QString .

Warning:  If the value of the Qt property changes after the style sheet has been set, it might be necessary to force a style sheet recomputation. One way to achieve this is to unset the style sheet and set it again.

ID  SelectorQPushButton#okButtonMatches all QPushButton  instances whose object name  is okButton .

第二个是通过object name来判断

比如QTMyWidget里定义了一个 QLabel* m_pLabelName;

给它设置一个objectname: m_pLabelName->setObjectName("Name");

然后就可以通过在CSS文档里添加下面的代码来set style

QTMyWidget QLabel#Name  {      backgroundnone;      colorwhite;  }  
QTMyWidget QLabel#Name { background: none; color: white; }  

回头重点强调第一个通过Property Selector来set style, 这一点可以跟自定义Property结合起来,功能强大。

QWidget已经有了很多默认的Property,我们还可以通过Qt宏Q_PROPERTY给widget添加自定义的Property,

Q_PROPERTY宏的定义:

Q_PROPERTY(type name


READ getFunction


[WRITE setFunction]


[RESET resetFunction]


[DESIGNABLE bool]


[SCRIPTABLE bool]


[STORED bool]


[USER bool])

使用比如

class QTMyWidget : public QFrame  {      Q_OBJECT      Q_PROPERTY(bool active READ active WRITE setActive)  ...  public:      bool active()const;      void setActive(bool active);  private:      bool    m_bActive;  }  
QTMyWidget[active="true"] { border-width: 4px 4px 4px 4px; }

这样就能设置QTMyWidget在active == true时的style了。

 

原创粉丝点击