Qt Style Sheet(简称qss)是QT用于美化界面,实现多种皮肤的机制。它和 Cascading Style Sheets (CSS)的使用方法非常相似。本文简单介绍了如何在Qt开发的应用程序中使用qss来优化皮肤。
1 Qt Style Sheet的使用方法
1.1 直接在程序代码中进行使用,使用setStyleSheet方法
1).对一个QApllication中的所有QLineEdit的背景色都设置为黄色:
nameEdit->setStyleSheet("{ background-color: yellow }");
2).对一个名为myDialog的QDialog中的所有QLineEdit的背景色都设置为黄色:
myDialog->setStyleSheet("QLineEdit { background-color: yellow }");
3).对一个名为myDialog的QDialog中的名为nameEdit 的QLineEdit的背景色设置为黄色:
myDialog->setStyleSheet("QLineEdit# nameEdit{ background-color: yellow }");
4).对一个名为nameEdit 的QLineEdit的背景色设置为黄色:
nameEdit->setStyleSheet("{ background-color: yellow }");
1.2 使用qss文件
步骤如下:
1) 创建qss文件,例如:cu.qss.
2) 根据qss语法,写自定义的内容(详见qss语法)
3) 引入qss文件,使界面效果生效。代码如下:
QString strQSS; //最终的QSS文件内容
QString strQssFile = “cu.qss”;
if (QFile::exists(strQssFile))
{
//存在就读取
QFile qFile(strQssFile);
qFile.open(QFile::ReadOnly);
strQSS = qFile.readAll();
qFile.close();
}
QApplication &a = *qApp;
a.setStyleSheet(strQSS);
2 qss语法
同css一样,qss也有由一个selector与一个declaration组成,selector指定了是对哪一个控件产生效果,而declaration才是真正的产生作用的语句。例如QPushButton{color:red},其中QPushButton是selector,而{}内的值为declaration。
2.1 特定类型控件设置属性
语法为selector{declaration}。
例:QPushButton { color: red }
QPushButton指定了是对所有的QPushButton或是其子类控件(如用户定义的MyPushButton)产生影响,而color:red表明所有的受影响控件的前景色都为red。
2.2 多个控件设置属性
语法为:selector1, selector2{declaration}
如果有几个selector指定了相同的declaration,用逗号(,)将各个选择器分开。
例:QPushButton, QLineEdit, QComboBox{ color: red }
这相当于:
QPushButton { color: red }
QLineEdit { color: red }
QComboBox{ color: red }
是对QPushButton ,QLineEdit 和QComboBox的前景色都设置为red。
2.3 特定名字的控件设置属性
语法为:selector#name{declaration}
用#将selector和控件的名字隔开。
例:QPushButton#MyPushButton{ color: red },
这只对名字为MyPushButton的QPushButton有效,对其他的QPushButton无效。
2.4 全部控件设置属性
语法为:*{ declaration }
将selector改为*,将对整个应用程序的所有控件有效。
例:
将整个应用程序的所有控件的字体大小都改为12px。
2.5 某个控件的子类设置属性
语法
对class所有widget子类控件都设置属性。
例:QDialog QPushButton{ color: red }
对所有QDialog中所有后代中的QPushButton的前景色都设置为红色。
2.6 多个属性设置
语法:selector{declaration1; declaration2;……}
declaration部份是一系列的(属性:值)对,使用分号(;)将各个不同的属性值对分开,使用大括号({})将所有declaration包含在一起。
例:
QPushButton# MyPushButton{
border-style: outset;
border-width: 2px;
border-color: beige;
}
此例子中设置了MyPushButton的背景色为红色,边框样式为outset,边框宽度为2px,边框颜色为米色。效果如下:
3 结语
Qt Style Sheet在绘制Qt开发的软件界面皮肤的功能非常强大,能够满足各种界面的需求。此文章只是对QSS的用法做了简单的介绍。在实际使用中,还需要多看Qt的帮助文档,并多加练习。