官網的樣式表鏈接:http://doc.qt.io/archives/qt-4.8/stylesheet.html
各種控件的樣式:http://doc.qt.io/archives/qt-4.8/stylesheet-reference.html
QSS語法:http://www.w3school.com.cn/css/css_syntax.asp
基本QSS語法
background-color:rgb(6, 168, 255); 背景色
color:red; 字體顏色
border-radius:5px; 邊框圓角半徑
border:2px solid green; 邊框2像素,實現,綠色
font:10pt; 字體大小10
改變樣式表的方法
1. UI控件右鍵
2. 程序添加
每一個控件都有setStyleSheet(const QString &styleSheet)方法,樣式字符串直接傳參即可,例:
ui.pushButton->setStyleSheet("QPushButton{background-color: white; color: rgb(100, 100, 100) ;}");
3. 添加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);
}
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文件中
4.QSS對應多個控件(Selector)
一個UI界面有很多控件,使用一個qss文件來指定樣式時,可以使用Selector來分別設置控件的樣式
屬性覆蓋:一個qss文件里,后面定義的style會覆蓋先前的style。
同一行中多個類型需要用逗號分隔
QPushButton, QLineEdit, QCheckBox
{
background: color: black;
}
- 屬性分類
例如:有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"));
[參考鏈接]
https://blog.csdn.net/qq_31073871/article/details/79943093
https://www.cnblogs.com/woniu201/p/10601671.html