文章目录
前言:
在现代软件开发中,用户界面的美观性和交互性是至关重要的。Qt Style Sheets(QSS)作为一种强大的样式定制工具,为开发者提供了类似于CSS的样式设置机制,使得界面设计更加灵活和多样化。通过QSS,开发者可以轻松地为Qt应用程序中的控件定义外观和行为,从而创建出既美观又具有良好用户体验的界面。本文将详细介绍QSS的选择器、样式属性以及如何利用这些工具来定制各种控件的样式,最终通过一个登录界面的设计示例,展示QSS在实际开发中的应用。
1. QSS 选择器
QSS 的选择器支持以下几种:
a.setStyleSheet("QPushButton { color : red; }");
这段代码中 QPushButton
就是 类型选择器了,QPushButton
也是 QWidget
的子类。
a.setStyleSheet(".QWidget { color : red; }");
这段代码中 .QWidget
是 类选择器,不会选中子类。
在开发中,期望不同的控件的样式不同,此时就需要使用 id 选择器了,因为 id 是唯一的。
// main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString style = "QPushButton { color: red; }";
style += "#pushButton_2 { color: green; }";
style += "#pushButton_3 { color: blue; }";
a.setStyleSheet(style);
Widget w;
w.show();
return a.exec();
}
此时当类型选择器 和 id选择器 选中同一个控件的时候,并且设置的样式是冲突的,此时,id选择器的优先级更高。
并集选择器:
QString style = "#pushButton_2, QLineEdit, QLabel{ color: red; }";
a.setStyleSheet(style);
2. 子控件选择器(Sub-Controls)
2.1. 示例:给 QComboBox 给下拉按钮加上图标
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString style = "QComboBox::down-arrow{ image: url(:/down.png)}";
a.setStyleSheet(style);
Widget w;
w.show();
return a.exec();
}
2.2. 示例:修改进度条颜色
QProgressBar::chunk {
background-color: #FF0000;
3. 伪类选择器
前面介绍的选择器,都是选中“控件”,伪类选择器,选中的控件的“状态”,“符合一定条件”的控件。
这些状态可以使用!
来取反. 比如 :!hover
就是鼠标离开控件时, :!pressed
就是鼠标松开时,
等等。
3.1. 代码示例: 设置按钮的伪类样式.
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString style = "QPushButton { color: red; }";
style += "QPushButton:hover { color: green; }";
style += "QPushButton:pressed { color: blue; }";
a.setStyleSheet(style);
Widget w;
w.show();
return a.exec()