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改為*,將對整個應用程序的所有控件有效。
例: *{font-size: 12px;}
將整個應用程序的所有控件的字體大小都改為12px。
2.5 某個控件的子類設置屬性
語法 Class widget{ declaration }
對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的幫助文檔,並多加練習。
