一、什么是Qt样式表
Qt样式表是一种强大的Qt机制,除了通过子类QStyle已经可以实现的功能之外,它还允许自定义小部件的外观。Qt样式表的概念、术语和语法深受HTML层叠样式表(CSS)的启发,但同时适应了Qt 的小窗体部件。
二、概述
Qt样式表的使用,对于应用,通常我们使用 QApplication::setStyleSheet() 函数来指定一个全局的样式;当然,对于指定的窗口部件,我们也可以使用 QWidget::setStyleSheet(). 来指定样式风格。
QLineEdit { background: yellow }
QCheckBox { color: red }
备注:通常我们在项目中使用Qt样式表的时候,往往会将风格样式写在一个个.css 的样式文件中,Qt程序运行时,从.css文件中读取样式,再调用setStyleSheet()方法设置;这样做有如下几个优点:
(1)方便用户自定义风格样式(在私有化定制软件中运用普遍)
(2)在不改变程序功能,只更新风格样式的情况下,无需重新编译程序;在线更新软件,也只需要更新css样式文本
三、语法
Qt样式表的术语和语法和CSS基本上是完全相同的。
语法格式:
selector declaration
eg:
// 指定某种类型的选择器的样式风格
QPushButton {background-color:red;}
// 同时指定多种选择器的相同样式
QLineEdit,QComboBox,QPushButton {color:black;}
// 指定某个具体控件的样式风格
QPushButton#myButton{color:white;}
四、选择器的类型(selector type)
通常,选择器遵循如下的语法:
Selector |
Example |
Explanation |
Universal Selector(全局选择) |
* |
匹配所有的控件 |
Type Selector(类型选择) |
QPushButton |
匹配QPushButton及其子类的实例。 |
Property Selector(属性选择) |
QPushButton[flat=“false”] |
匹配QPushButton实例中 flat属性为false的控件。 你可以使用这个选择器去测试支持 QVariant::toString() 函数的Qt property 属性系统。 此外,还支持特殊类属性作为类的名称。同时,此选择器还支持一些动态的属性。 I我们可以使用 “~=” 来替换 “=” 去检测Qt的属性系统中,类型为 “QStringList” 的属性值 是否 包含给定的 “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.
|
Class Selector(类选择) |
.QPushButton |
匹配QPushButton的所有实例,但是不包含其子类,其效果等同于我们在使用属性选择时: * [class=“QPushButton”]
|
ID Selector(ID 选择) |
QPushButton#okButton |
匹配所有QPushButton中名称为okButton的控件 |
Descendant Selector(后代选择) |
QDialog QPushButton |
匹配所有父类为QDialog 的QPushButton(或者QPushButton的子类、孙子类等)的实例控件对象 |
Child Selector(子类选择) |
QDialog > QPushButton |
相比较“后代选择”,“子类选择”是一种范围缩小的选择,他只能允许选择QDialog 下的QPushButton类型的直接孩子控件。 |
代码及示例:
【1】Universal Selector 全局选择
a.setStyleSheet("*{color:red;}");
【2】Type Selector 类型选择
// 只改变pushbutton的样式风格
a.setStyleSheet("QPushButton {color:red;}");
【3】Property Selector 属性选择
// 只改变pushbutton中flat属性为false的控件的样式 ==> 过滤控件
a.setStyleSheet("QPushButton[flat="false"] {color:red;}");
【4】class Selector 类选择
// 只改变pushbutton中flat属性为true的控件的样式 ==> 过滤控件
#ifndef CLASS_SELECTOR
a.setStyleSheet(".QPushButton[flat=\"true\"] {color:red;}");
#elif PROPERTY_SELECTOR
a.setStyleSheet("* [class=\"QPushButton\"][flat=\"false\"{color:red;}");
#else
【5】ID Selector (ID 选择)
a.setStyleSheet("QPushButton#pushButton {color:red;}");
【6】 后代选择和子类选择用法就不在此处展示了
五、子控件
对于某些复杂的组合控件,会包含一些子类控件,譬如 QComboBox 的drop-down 按钮,或 QSpinBox 的 “up“ 和 ”down arrows“
QComboBox::drop-down { image: url(dropdown.png) }
QComboBox {
margin-right: 20px;
}
QComboBox::drop-down {
subcontrol-origin: margin;
}
QComboBox::down-arrow {
image: url(down_arrow.png);
}
QComboBox::down-arrow:pressed {
position: relative;
top: 1px; left: 1px;
}
附: Box模型