使用Qt Style Sheet(2)by buptyoyo 2009-10-30 16:51
2, 解决冲突
a) 使用object name
i. 在程序里面要先设置控件的,如:
btnOne = new QPushButton(centralWidget);
btnOne->setObjectName(QString::fromUtf8("btnOneCh"));
ii. 这样,我们有了一个object name为btnOneCh的QPushButton,试验一下,使用指定object name的方式,如:
QPushButton#btnOneCh { color: red }
QPushButton { color: white }
可以看出,btnOncCh的color变成了red
b) 使用伪选择器,如hover,press,enabled等,如:
i. 按扭“1”是disable了的,
QPushButton:!enabled {color: white}
c) 所有的类型选择器都有一个共同的特性,就是如果有两个属性冲突了的话就会以最后出现的一个为准,如:
QPushButton { color: red }
QAbstractButton { color: gray }
由于QPushButton为QAbstractButton的子类,如果只设置QAbstractButton的可以想像结果是所有的QPushButton都为gray, 如果只设置QPushButton的所有QPushButton都会为red,当两个都能设置起效的时候,以在文本上最后出现的为准,所以结果为Grey
d) 当然其中如果有#指定了object name,他所设置的优先级是最大的,具体规则可以参考:http://www.w3.org/TR/CSS2/cascade.html#specificity,或是
http://pepper.troll.no/s60prereleases/doc/stylesheet-syntax.html#conflict-resolution
QPushButton#btnOneCh { color: red }
QPushButton { color: blue }
QAbstractButton { color: gray }
虽然QAbstractButton在最后,但是之前有#btnOneCh指定了QPushButton“一”的color为red所以最后显示也是“一”为red。
3, 级联效应
a) 子类可以继承父类的StyleSheet,但是如果子类里面设置了StyleSheet与父类里在设置的有冲突,那么当然会优先考虑子类自己的,同样,如果在qApp时面设置了,但是在某一个特定控件里面也设置,如果有冲突,也是优先控件自己的,例如,我在程序时面设置了:
btnOneEn->setStyleSheet("QPushButton { color: red }");
而,当我再设置qApp时,如果,将QPushButton的color设置成grey的,那么结果是对于btnOneEn这个QPushButton来说他的颜色还是red。
这就是为什么这里设置为grey了btnOneEn却还是red的。
b) 如果我们对一个控件设置StyleSheet为:
QPushButton* myPushButton;
myPushButton->setStyleSheet("* { color: blue }");
其实他和设置为:
myPushButton->setStyleSheet("color: blue");
效果相同,只是后一种设置不会对QPushButton的子类产生作用,但第一种却会。
4, 继承性
a) 与CSS不同的一点,在CSS box模型中,如果一个元素在别一元素的里面,那么里面的元素会自动继承外面元素的属性,但QSS里面不会,如:
一个QPushButton如果放在一个QGroupBox里面,如果:
qApp->setStyleSheet("QGroupBox { color: red; } ");
并不代表在QGroupBox里面的QPushButton也会有color:red的属性,如果要想有的话要显示写明,如:
qApp->setStyleSheet("QGroupBox, QGroupBox * { color: red; }");
或者在应用程序里面也可以用QWidget::setFont等来设置到子控件的属性。
5, Namespace冲突
a) 类型选择器能够使用到一个特定的类型,如:
class MyPushButton : public QPushButton {
// ...
}
qApp->setStyleSheet("MyPushButton { background: yellow; }");
因为QSS使用QObject::className来判断要赋与style sheet的控件类型,如果一个用户定义控件类型在一个namespace里面的话,QObject::className会返回<namespace>::<classname> 的名字,这和子控件选择器的语法相冲突,为了解决此问题,使用“--”来代替“::”,比如:
namespace ns {
class MyPushButton : public QPushButton {
// ...
}
}
qApp->setSytleSheet("ns--MyPushButton { background: yellow; }");
6, 设置对像属性
a) 如果在程序里面使用Q_PROPERTY设置的属性,可以在qss里面使用:qproperty-<property name>的形式来访问并设置值。如:
MyLabel { qproperty-pixmap: url(pixmap.png); }
MyGroupBox { qproperty-titleColor: rgb(100, 200, 100); }
QPushButton { qproperty-iconSize: 20px 20px; }
如果属性引用到的是一个由Q_ENUMS申明的enum 时,要引用其属性名字要用定义的名称而不是数字。
引用:
使用Qt Style Sheet(2)--QSS语法
最新推荐文章于 2023-03-03 16:16:54 发布