Qt第十二章 样式表

样式表

文章目录

1.样式表

盒子模型

2.选择器

  • 样式表语法,选择器{属性1:值;属性2:值;}
  • 如果只有单个属性,分号可以不加

选择器类型

选择器 示例 描述
通用选择器 * 匹配所有控件
类型选择器 QPushButton 匹配给定的控件,包括子类
类选择器 .QPushButton 匹配给定的控件,不包括子类
属性选择器 QPushButtonflat="false" 匹配给定类型中符合属性的控件
ID选择器 QPushButton#closeButton 匹配给定类型,且对象名为closeButton的控件
子孙对象选择器 QDialog QPushButton 匹配给定类型的子孙控件
子对象选择器 QDialog>QPushButton 匹配给定类型的直接子控件
辅助子控件选择器 QComboxBox::drop-down 复杂对象子控件
伪状态选择器 QPushButton:hover 控件的特定状态下的样式
并集选择器 QPushButton,QLineEdit 若干基础选择器可以写一起,逗号隔开
css 复制代码
QPushButton[down = "false"]{color:yellow;background:red}
QLabel[text = "TextLabel"]{color:red}

同时在UI和文件代码里设置样式表会冲突,只会生效ui里设置的

伪状态选择器Pseudo-State

css 复制代码
QPushButton:hover{color:red}
状态 描述
:disabled 控件禁用
:enabled 控件启用
:focus 控件获取输入焦点
:hover 鼠标在控件上悬停
:pressed 鼠标按下
:checked 控件被选中
:unchecked ~
:indetetminate 控件部分被选中
:open 控件打开
:closed ~
:on 控件可以切换,且处于on状态
:off ~
! 对以上状态的否定

3.控件示例

css 复制代码
QLabel#label{
 font-family: "微软雅黑";
font-size: 20px;
 font-style: italic;
color: rgb(239,204,180);
border-image:url("C:/Users/PVer/Pictures/Resource/派蒙.jpeg")
}

QPushButton{
/*上右下左设置padding间距*/
padding:20px 0px 0px 50px;
border: 3px solid black;
border-radius: 10px;
background-color:red;
}

QLineEdit{
border-top:2px solid yellow;
border-right:2px dotted black;
border-top-left-radius:10px;
border-left:3px solid black;
}

QLabel#label_2{
background-image:url("C:/Users/PVer/Pictures/Resource/xiaoku.png");
background-repeat:no-repeat;
background-position:left top;
}

QLabel#label_2:hover{
background-color:green;
}

QPushButton:pressed{
background-color:orange;
}

QCheckBox::indicator{
background-color:grey;
border-radous:5px;
}

QCheckBox::indicator:checked{
background-color:black;
}

QCheckBox::indicator:!checked:hover{
background-color:green
}

4

.细节、注意事项

继承自QWidget的类,设置qss样式表没有效果,需要重写paintEvent

c 复制代码
 void CustomWidget::paintEvent(QPaintEvent *)
 {
     QStyleOption opt;
     opt.initFrom(this);
     QPainter p(this);
     style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
 }

而且必须使用Q_OBJECT宏

相关推荐
用户805533698033 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner3 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz8 天前
QML Hello World 入门示例
qt
xcyxiner11 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner12 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner12 天前
DicomViewer (添加模型类)3
qt
xcyxiner13 天前
DicomViewer (目录调整) 2
qt
xcyxiner13 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00614 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术14 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript