Qt 样式设置
Qt 帮助文档 The Style Sheet Syntax
CSS 教程
CSS2 Selectors
样式语法
Qt Style Sheet 语法不区分大小写:
指定控件 Selector Types
对控件设置样式是可以限定范围,如根据控件名字,或者某一类控件但不包括子控件等,常用的类型如下:
如根据 Object name 来设置某类控件样式:
QWidget#widget_a,QWidget#widget_b
{
background-color:#000000;
}
盒子模型 The Box Model
能自定义样式的控件
Qt 中查看 List of Stylable Widgets 的位置如下:
部分截图:
Sub-Controls
List of Sub-Controls 位置:
控件的状态 Pseudo-States
控件在不同状态下的样式,如 QPushButton 在按下(pressed)或悬浮(hover)状态下设置不同的背景颜色。
属性
List of Properties 和 List of Sub-Controls 查找方法相同。
内置图标
List of Icons 和 List of Sub-Controls 查找方法相同。
QIcon icon = QApplication::style()->standardIcon(QStyle::QStyle::SP_ComputerIcon);
ui->pushButton->setIcon(icon);
QPixmap pic = icon.pixmap(icon.actualSize(QSize(64,64)));
ui->label->setPixmap(pic);
多个设置冲突
同一个控件同时在 .qss
文件,ui
文件和代码中设置样式,其优先级为:
代码中指定样式 > ui
文件中通过 styleSheet
设置样式 > .qss
中设置样式。
层叠样式 Cascading
继承规则 Inheritance
子窗口不继承父窗口样式
在界面中指定某个窗口的样式,如背景颜色等,指定名称,不影响子控件。
ID selectors
介绍: 5.9 ID selectors
如:在一个 QFrame
中添加一个 QComboBox
,将 QFrame
的背景设置为透明样式,且不指定具体名字,发现 QComboBox
的下拉窗体背景颜色无法设置,而指定 QFrame
名字后正常。
QFrame
不设置透明样式,指定背景颜色,在里面添加的 QComboBox
的下拉框每个条目的背景颜色是 QFrame
的背景颜色,指定 QFrame
名字后正常。
移除控件旧样式
添加 .qss 文件
可以建一个 .qss
文件来设置应用程序的样式,或者建立几种不同的风格可以切换,如对所有的按钮统一设置样式,保持风格统一,程序里加载 .qss
文件。
程序的目录如下:
工程中添加资源文件方法:Qt资源文件。
QFile file(QString(":/resource/style.qss"));
file.open(QFile::ReadOnly);
QString strQss = QLatin1String(file.readAll());
qApp->setStyleSheet(strQss);
同一个控件同时在 .qss
文件,ui
文件和代码中设置样式,其优先级为:
代码中指定样式 > ui
文件中通过 styleSheet
设置样式 > .qss
中设置样式。
Qt 预置颜色
QLineEdit 样式设置
可以在 .qss
的文件统一设置样式。
.QLineEdit{
width:400px;
height:40px;
font-family: "Microsoft YaHei";
font-size: 16px;
padding: 2px;
color:blue;
background-color: #BDB76B;
selection-color: red;
seletion-background-color: #696969;
}
.QLineEdit[echoMode="2"] {
lineedit-password-character: 9679;
}
.QLineEdit:focus{
border: 1px solid #DC143C;
}
.QLineEdit:hover{
border: 1px solid #DB7093;
}
.QLineEdit:!enabled{
color:gray;
background-color: #7FFF00;
}
selection-color
设置选中文本时的文本的颜色,seletion-background-color
设置选中文本时的背景颜色。
width
和 height
可以在 ui 界面设置,界面设置后以界面设置的为准。
QPushButton
CSS 按钮
Qt 帮助文档 Qt Style Sheets Examples ----- Customizing QPushButton
.QPushButton{
background-color: black;
border: 2px solid #4CAF50; /* Green */
border-radius: 50%;
color: white;
font: bold 14px;
padding: 5px;
min-height: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
.QPushButton:disabled{
background-color: #696969;
color:#C0C0C0;
}
.QPushButton:hover{
background-color: #696969;
color:#C0C0C0;
}
.QPushButton:pressed{
background-color: #696969;
color:#C0C0C0;
}
.QPushButton:checked{
color: #808000;
background-color: #8B4513;
}