QSS简介
QSS(Qt Style Sheets)是Qt框架中用于自定义控件外观的样式表语言,类似于CSS。通过QSS可以修改控件的颜色、字体、边框等属性,实现界面美化。
基本语法结构
QSS语法与CSS类似,由选择器和声明块组成:
QPushButton { color: red; background-color: white; }其中QPushButton是选择器,花括号内是属性-值对。
常用属性
颜色和背景:
color: #FF0000; /* 文本颜色 */ background-color: #FFFFFF; /* 背景色 */ border: 1px solid black; /* 边框 */字体:
font-family: "Arial"; font-size: 14px; font-weight: bold;尺寸和边距:
padding: 5px; /* 内边距 */ margin: 10px; /* 外边距 */ min-width: 100px;选择器类型
类选择器(常用):
.QPushButton { ... } /* 所有QPushButton实例 */ID选择器:
#myButton { ... } /* 对象名为myButton的控件 */子控件选择器:
QComboBox::drop-down { ... } /* QComboBox的下拉箭头 */状态选择器:
QPushButton:hover { ... } /* 鼠标悬停状态 */ QCheckBox:checked { ... } /* 选中状态 */应用QSS的方法
通过代码设置:
widget->setStyleSheet("QPushButton { color: red; }");加载外部文件:
QFile file("style.qss"); file.open(QFile::ReadOnly); qApp->setStyleSheet(file.readAll());注意事项
属性继承性:子控件默认不继承父控件的样式,需显式设置。
优先级规则:ID选择器 > 类选择器 > 类型选择器。
性能优化:避免频繁动态修改样式,尽量使用外部文件。
调试技巧:使用Qt Designer实时预览样式效果。
高级特性
渐变背景:
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 white, stop:1 black);盒模型:理解margin、border、padding和content的层次关系。
伪状态组合:
QPushButton:checked:hover { ... } /* 选中且悬停的状态 */