QSS 改变样式表

官网的样式表链接: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来分别设置控件的样式

  1. 属性覆盖:一个qss文件里,后面定义的style会覆盖先前的style。

  2. 同一行中多个类型需要用逗号分隔

QPushButton, QLineEdit, QCheckBox
{
    background: color: black;
}
  1. 属性分类

例如:有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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容