Qt樣式表示是一個可以自定義部件外觀的十分強大的機制
使用代碼設置樣式表
ui->pushButton->setStyleSheet("background:yellow"); ui->horizontalSlider->setStyleSheet("background:blue");
對所有的相同部件使用相同的樣式表
setStyleSheet("QPushButton{background:yellow}QSlider{background:blue}");
在設計模式中設置樣式表
界面右擊,在彈出的菜單樣式中選擇“改變樣式表”。在編輯樣式對話框輸入代碼:
QPushButton{},然后單擊上面“添加顏色”。如果為單一部件添加樣式表,需選中該部件后右擊“改變樣式表”。
Qt樣式表語法
樣式規則
一個樣式規則由一個選擇符和聲明組成
QPushButton{color:red}
QPushButton是選擇符,{color:red}是聲明,color是屬性,red是值。
一些選擇符可以指定相同的聲明,例如:
QPushButton,QLineEdit,QComBox{color:red}
屬性之間使用分號隔開,例如:
QPushButton{color:red;background-color:white}
在Qt Style Sheets Reference 關鍵字對應對文檔中,List of Properties一項查看Qt樣式表所支持的屬性
選擇符類型
* 匹配所有部件
QPushButton 匹配QPushButton實例和他的所有子類
QPushButton[flat = "false"] 匹配QPushButton的屬性flat為false的實例
.QPushButton 匹配所有QPushButton實例,但不包含他的子類
QPushButton#okButton 匹配QPushButton中以okButton為對象名的實例
自定義部件外觀與換膚
QMainWindow{
background - image: url(:/image/beijing01.png);//背景圖片
}
/*鼠標懸停在按鈕上*/
QPushButton:hover{
background-color:rgba(100,255,100,100);
}
換膚
QFile file(":/qss/my.qss");
file.open(QFile::ReadOnly);
QString styleSheet = tr(file.readAll());
qApp->setStyleSheet(styleSheet);