Qt:StyleSheet使用总结

转眼七年过去了,我是一个彻底拥抱过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)方法,样式字符串直接传参即可,例:

1
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;
}

读取配置文件设置指定按钮样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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.同一行中多个类型需要用逗号分隔。

1
2
3
4
QPushButton, QLineEdit, QCheckBox
{
background: color: black;
}

3.属性分类

例如:有6个PushButton控件,3个设置为样式一,另外三个设置为样式二

方法一:

设置前3个控件的whatsThis为style1,后三个控件为style2

修改StyleSheet.qss文件内容

1
2
3
4
5
6
7
8
9
10
11
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。

1
2
3
4
5
QPushButton#pushButton1
{
background-color: rgb(63,141,215);
color:red;
}

最后在程序的入口函数设置如下代码:

1
2
3
4
QApplication a(argc, argv);

StyleDialog styleDialog;
a.setStyleSheet(styleDialog.ReadQssFile(":/qtlearn/Resources/StyleSheet.qss"));

最后附上一张使用QSS技术仿的百度网盘界面:

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×