QSS 选择器

通用选择器 *

* 作为选择器,作用于所有的 widget。

类型选择器

类名 作为选择器,作用于它自己和它的所有子类。

1
2
3
QFrame {
   background: gray;
}

 

类选择器

. + 类名 或者 . + class 的属性值 作为选择器(使用 setProperty(“class”, “QSSClassName”) 设置),只会作用于它自己,它的子类不受影响,注意和类型选择器的区别。

1
2
3
4
5
6
app.setStyleSheet(".QWidget { background: gray; }"
                  ".RedButton { background: magenta; }");

// .RedButton 将作为类选择器
openButton->setProperty("class",  "RedButton");
closeButton->setProperty("class", "RedButton");

 

ID 选择器

# + objectName 作为选择器,只作用于用此 objectName 的对象

1
2
3
4
5
6
// #openButton 和 #closeButton 作为 ID 选择器
app.setStyleSheet(".QWidget { background: gray; }"
                  "#openButton, #closeButton { background: magenta; }");
    
openButton->setObjectName("openButton");
closeButton->setObjectName("closeButton");

属性选择器

选择器[属性="值"] 作为选择器,这个属性可用通过 object->property(propertyName) 访问的,Qt 里称为 Dynamic Properties

如上面的程序, openButton 和 closeButton 的背景是洋红色的,但是 saveButton 不受影响,也可以使用属性选择器来实现:

1
2
3
4
5
app.setStyleSheet(".QWidget { background: gray; }"
                  "QPushButton[level='dangerous'] { background: magenta; }");

openButton->setProperty("level",  "dangerous");

包含选择器

英语叫做 Descendant Selector,descendant 的表达比较到位。

选择器之间用空格隔开,作用于 Widget 的 子Widget子Widget 的 子Widget,……,子子孙孙,无穷尽也。

1
2
3
4
5
6
7
8
9
10
11
QFrame {
	background: gray;
}

/* 设置 QFrame 中的 QPushButton 的 QSS */
QFrame QPushButton {
    border: 2px solid magenta;
    border-radius: 10px;
    background: white;
    padding: 2px 15px;
}

子元素选择器

选择器之间用 > 隔开,作用于 Widget 的直接 子Widget,注意和包含选择器的区别。

1
2
3
4
5
6
7
8
9
10
QFrame {
	background: gray;
}
    
QFrame > QPushButton {
    border: 2px solid magenta;
    border-radius: 10px;
    background: white;
    padding: 2px 15px;
}

伪类选择器

选择器:状态 作为选择器,支持 ! 操作符,表示 

1
2
3
QPushButton:hover { color: white }
QCheckBox:checked { color: white }
QCheckBox:!checked { color: red }

 

Subcontrol 选择器

选择器::subcontrol 作为选择 Subcontrol 的选择器。

有些 widget 是由多个部分组合成的,例如 QCheckBox 由 icon(indicator) 和 text 组成,可以使用 选择器::subcontrol 来设置 subcontrol 的样式:

1
2
3
4
5
6
7
8
QCheckBox::indicator {
    width: 20px;
    height: 20px;
}

QCheckBox {
    spacing: 8px;
}
  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值