概述
轉眼七年過去了,我是一個徹底擁抱過MFC的人,記得老大的一個需求要把按鈕做成圓角,並添加背景顏色,做前端html的可能認為很簡單,然而放到MFC上那可真的是很...很麻煩的,自定義類繼承Button ,新手估計還搞不定,怎么也有上百行代碼,實在不友好,Qt誕生大大簡化了這些工作,只需要使用QSS(Qt Style Sheet)就可以輕松做到,最近詳細了解了QSS,做了個百度網盤的登錄界面,整理好我會把源碼放出來,供大家參考。
QSS語法
background-color:rgb(6, 168, 255); 背景色
color:red; 字體顏色
border-radius:5px; 邊框圓角半徑
border:2px solid green; 邊框2像素,實現,綠色
font:10pt; 字體大小10
設置QSS方法
方法一:UI界面設置
鼠標到按鈕上右鍵,"改變樣式表",在編輯樣式表對話框中添加QSS樣式。

方法二:程序添加
每一個控件都有setStyleSheet(const QString &styleSheet)方法,樣式字符串直接傳參即可,例:
ui.pushButton1->setStyleSheet("QPushButton{background-color: white; color: rgb(100, 100, 100) ;}");
方法三:通過QSS文件添加
新建文件StyleSheet.qss文件,添加內容如下:
/*按鈕靜止無操作樣式*/ QPushButton { background-color:rgb(255,255,255); color:rgb(6,168,255); border:2px solid rgb(6,168,255); font-size:14px; border-radius:10px; } /*鼠標懸停在按鈕*/ QPushButton:hover { background-color: rgb(212,243,255); color:rgb(6,168,255); border:2px solid rgb(6,168,255); border-radius:14px; } /*鼠標按下按鈕*/ QPushButton:pressed { background-color: rgb(175,232,255); color:white; border:2px solid rgb(6,168,255); border-radius:14px; }
讀取配置文件設置指定按鈕樣式:
StyleDialog::StyleDialog(QWidget *parent) : QDialog(parent) { ui.setupUi(this); QString strStyle = ReadQssFile("StyleSheet.qss"); ui.pushButton2->setStyleSheet(strStyle); } StyleDialog::~StyleDialog() { } QString StyleDialog::ReadQssFile(const QString& filePath) { QString strStyleSheet = ""; QFile file(filePath); file.open(QFile::ReadOnly); if (file.isOpen()) { strStyleSheet = QLatin1String(file.readAll()); } return strStyleSheet; }
實際項目中一般qss文件直接添加到資源里面,一起打包到EXE文件中,這樣文件不會直接暴露給用戶。

Selector
一個UI界面有很多控件,使用一個qss文件來指定樣式時,可以使用Selector來分別設置控件的樣式
1.屬性覆蓋,一個qss文件里,后面定義的style會覆蓋先前的style。
2.同一行中多個類型需要用逗號分隔。
QPushButton, QLineEdit, QCheckBox
{
background: color: black;
}
3.屬性分類
例如:有6個PushButton控件,3個設置為樣式一,另外三個設置為樣式二
方法一:
設置前3個控件的whatsThis為style1,后三個控件為style2

修改StyleSheet.qss文件內容
QPushButton[whatsThis="style1"] { background-color: rgb(63,141,215); color:green; } QPushButton[whatsThis="style2"] { background-color: rgb(63,141,215); color:red; }
方法二:
直接在qss文件里指定object name,不推薦這種方式,6個控件需要些六遍,分別指定object name。
QPushButton#pushButton1 { background-color: rgb(63,141,215); color:red; }
最后在程序的入口函數設置如下代碼:
QApplication a(argc, argv); StyleDialog styleDialog; a.setStyleSheet(styleDialog.ReadQssFile(":/qtlearn/Resources/StyleSheet.qss"));
最后附上一張使用QSS技術仿的百度網盤界面:


