QT qss样式表案例

ID选择器

test.qss样式表文件内容如下:

如下样式表中通过 ID选择器指定控件

如下是QPushButton控件的obejctname分别为btn1、btn2和btn3

bash 复制代码
QWidget{
	border:1px solid red;
	background-color:#f0f0f0;  /*浅灰色背景*/
}

QPushButton#btn1, QPushButton#btn2, QPushButton#btn3
{
    border:1px solid blue;    /*按钮蓝色边框*/
    background-color:white;  /*白色背景*/
    min-height: 30px; /* 确保按钮有足够高度显示边框 */
}

QLabel{
	border:1px solid blue;
	background-color:#f0f0f0;  /*浅灰色背景*/
	font-size:20px;
}

代码中读取test.qss文件并全局设置

bash 复制代码
//从test.qss样式表文件中读取并全局设置样式表
    QFile file(":/style/test.qss");
    if (file.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(file.readAll());
        file.close();
        qDebug() << "Loaded QSS:" << styleSheet; // 在输出台查看内容
        qApp->setStyleSheet(styleSheet);
    }

代码中设置QPushButton的objectname如下:

bash 复制代码
QPushButton *button = new QPushButton("btn1", &window);
    button->setObjectName("btn1");
    QPushButton *button2 = new QPushButton("btn2", &window);
    button2->setObjectName("btn2");
    QPushButton *button3 = new QPushButton("btn3", &window);
    button3->setObjectName("btn3");

属性选择器

如果想要为某个按钮设置属性,如下为button设置button_type属性值为normal,button2设置button_type属性值为warning.

bash 复制代码
button->setProperty("button_type", "normal");
button2->setProperty("button_type", "warning");

同时test.qss样式针对不同属性设置不同样式表格式

bash 复制代码
QPushButton[button_type="normal"]
{
    border:1px solid blue;    /*按钮蓝色边框*/
    background-color:white;  /*白色背景*/
    min-height: 30px; /* 确保按钮有足够高度显示边框 */
}

QPushButton[button_type="warning"]
{
    border:1px solid green;    /*按钮蓝色边框*/
    background-color:white;  /*白色背景*/
    min-height: 30px; /* 确保按钮有足够高度显示边框 */
}

另外:

重要提示:如果在程序运行过程中通过代码改变了控件的属性,需要调用

widget->style()->unpolish(widget);

widget->style()->polish(widget);来强制刷新样式,或者重新设置整个窗口的样式表才能立即使样式生效

后代选择器(结构化限定)

如果这三个按钮都放在一个特定的父控件里(比如一个名为buttonContainer的QWidget)

样式表写法:

bash 复制代码
/* 匹配 ID 为 buttonContainer 的控件内的所有 QPushButton */
#buttonContainer QPushButton {
    border: 1px solid blue;
    background-color: white;
    min-height: 30px;
}

代码中的设置:为存放按钮的容器设置一个objectName。

bash 复制代码
// 假设有一个QWidget容器存放这些按钮
ui->buttonContainer->setObjectName("buttonContainer");

总结

相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能13 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G13 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt