使用QT中的QT Style Sheet功能

转载地址:http://blog.csdn.net/snailjava/article/details/6018924

我需要一个将Qt4中QPushButton按钮在获得焦点时背景色高亮的功能,如果要写代码很麻烦:)

使用Qt Sytle Sheets的功能后代码变的非常简单和干净:)

我是这样使用的

setStyleSheet("QPushButton:focus{background-color: red;}");

就会有按钮获得焦点高亮的作用

image  获得焦点时按钮红色高亮:)

由此体会到Qt4的Qt Style Sheets的功能的强大:)边学习边做些笔记以供还没有使用这个功能但又想方便的制定UI的朋友:)

Qt Style Sheets是什么?

Qt Style Sheets

Qt Style Sheets are a powerful mechanism that allows you to customize the appearance of widgets, in addition to what is already possible by subclassingQStyle. The concepts, terminology, and syntax of Qt Style Sheets are heavily inspired by HTML Cascading Style Sheets (CSS) but adapted to the world of widgets.

Qt Style Sheets能做什么?

#1 能让你的界面看上去更炫(那为什么要更炫呢?这个问题要看你自己了,我们公司做嵌入式产品的,设备上的界面的外观还是非常重要的:)

image

#2 能够要你实现同样的功能写更少的代码,比如我第一次使用Qt Style Sheets的

setStyleSheet("QPushButton:focus{background-color: red;}"); 的用法

这两个好处应该足够吸引一些人来使用这个功能,是否还有其他好处那我就不知道了,我现在就看到这两个好处就直流口水想用了:)

 

在哪里找到Qt Style Sheets的学习资料和使用例子?

具体的一些参考资料可以打开QT的assistant应用程序(API和使用说明文档)

输入关键字 Qt Style Sheets 查询,这个玩QT4的应该都会吧:)

image 

 

Qt Style Sheets如何使用?

如何使用的话主要参考assistent中的 The Style Sheet Syntax 一章

Style Rules

Style sheets consist of a sequence of style rules. A style rule is made up of a selector and a declaration. The selector specifies which widgets are affected by the rule; the declaration specifies which properties should be set on the widget. For example:

 QPushButton { color: red }
一个样式表(StyleSheets)有多个样式规则(StyleRules),每个样式规则有一个selector(我就不乱翻中文了,哈哈)和一个声明(declaration)。
selector指定这个规则可以影响哪些组件。声明(declaration)指定哪些属性作用于这些被影响的组件。
 
 
那意味着我们学习好样式规则就可以了:)样式规则是最主要的单位 一个样式规则是由A+B来组成的 A是selector selector的语法有7种,参考上面有,我就不写了。规律就是除了可以写组件名字,还可以通过一些符号和行为将组件来过滤 比如 QPushButton[flat="false"] 表示flat属性为false的所有QPushButton QPushButton#okButton 表示名字为okbutton的所有QPushButton * 表示所有的QPushButton 其他几种不实用(对我来讲不实用,要用的时候再去看,我先学这四个,哈哈) 除了通过[]和#来过滤出需要被影响的组件 还可以使用::和:符号来进行过滤出更细级别的组件,也即是我一开始所用来做QPushButton聚焦时的效果 ::符号我现在还没用到,具体可以做哪些设置,见Qt Style Sheets Reference的List of Sub-Controls。 :符号对我现在来讲比较有用,可以控制跟组件进行交互时的组件外观 
QPushButton:hover { color: white }
QRadioButton:!hover { color: red }
QCheckBox:hover:checked { color: white }     链式的,可以组合:符号,哇,厉害~~
我所使用的QPushButton:focus{background-color: red;} 
 
B是declaration

The declaration part of a style rule is a list of propertyvalue pairs, enclosed in braces ({}) and separated with semicolons. For example:

声明就是用 {}括起来的属性列表(0到多个吧),一个属性就是 键+ 冒号:+一个值

 QPushButton { color: red; background-color: white }
 
 

以上如果能理解,刚好是一个能使用QtStyleSheets的最小子集,QtStyleSheets具体的一些的其他用法和特殊用法可以看Assistant的资料,边

自己实践可以很快的掌握其他用法,我需要使用QtStyleSheet的地方大概就这么多,所以只写了这么多:)有不明白的地方或者错误的地方可以留言,

多讨论可以更快的学习知识,不是吗:)还省自己力气,呵呵                                                    ------飞羽飞之猪  2010年11月18日

猜你喜欢

转载自blog.csdn.net/wang15061955806/article/details/73033175
今日推荐