当前位置:网站首页>Use QSS to style the form
Use QSS to style the form
2022-07-29 05:41:00 【cloud_ yq】
This article is mainly correct Official documents Translation .
One 、Qss Functions and rules
Qss(Qt style sheet) Is a style text specification , have access to QApplication::setStyleSheet() To set the style of the entire application or use QWidget::setStyleSheet() Set up a QWidget( Including its subclasses ) The style of the form .Qss Has cascading properties , That is, assume that multiple style sheets are set at different levels , that Qt Valid style sheets will be derived from all set style sheets . Style sheets allow you to perform all types of customization , These customizations only use QPalette It is difficult or impossible to implement . for example , You want a yellow background as a mandatory field , Red text acts as a potentially destructive button , Or fancy check boxes , Style sheets are the answer .
The style rule consists of a selector (selector) And a statement (declaration) form . Selectors specify which Widget Affected by this rule ; The declaration specifies that it should be in Widget Which properties are set on the . for example :QPushButton { color: red } ,QPushButton yes selector,{color:red} yes declaration, This rule specifies QPushButton And its subclasses should use red as the foreground color ( text color ). The declarative part of a style rule consists of a {property:value} The table consists of , for example :QPushButton { color: red; background-color: white }. When multiple types of Widget Have the same {property:value} Can also be in selector Parts are separated by commas , for example QPushButton, QLineEdit, QComboBox { color: red }.
Two 、selector type
Qt Style sheets support CSS2 All selectors defined in . The following table summarizes the common selector types .
selector | Example | explain |
Universal Selector | * | Match all Widget |
Type Selector | QPushButton | Match all QPushButton Component and its subcomponents |
Property Selector | QPushButton[flat="false"] | Match all non planar (flat="false") Attribute QPushButton. The objects filtered in this filter need to be set first QVariant Supported type properties (setProperty(“flat”, “false”)). Warning : If after the style sheet settings Qt The value of the property changes , You may need to force the style sheet to recalculate . One way to do this is to unset the stylesheet and set it again . |
Class Selector | .QPushButton | matching QPushButton Components , But it does not include its subclasses . |
QPushButton#okButton | When matching all object names okButton Of QPushButton Control | |
Descendant Selector | QDialog QPushButton | matching QPushButton All instances of , They are QDialog Descendants of controls ( Child controls 、 Sun et al ). |
Child Selector | QDialog > QPushButton | matching QPushButton All instances of , They are QDialog Direct child of . |
3、 ... and 、Property type
The following table lists them Qt Common properties supported by style sheets ( See... For all properties https://doc.qt.io/qt-5/stylesheet-reference.html). What values can be assigned to an attribute depends on the type of attribute . Unless otherwise stated , The following properties apply to all widgets . Marked with an asterisk * The properties of are specific to Qt Of , stay CSS2 or CSS3 There are no identical attributes in the .
Proprty | type | explain |
alternate-background-color | Brush | alternate-background-color It is mainly used for QAbstractItemView Subclass , Used to set the alternate background color of the view text ( You need to set the alternate background color property of the view ). for example :
|
background | Background | Set the abbreviation of the form background , Including settings
|
background-color | Brush | Set the background color of the form . for example :QLabel { background-color: yellow } QLineEdit { background-color: rgb(255, 0, 0) } |
background-image | Url | Set the background picture of the form , The translucent part of the image allows the background color to pass through . example :QFrame { background-image: url(:/images/hydro.png) } |
background-repeat | Repeat | Set whether the background image repeatedly fills the background origin rectangle , And how to repeatedly fill . The default is to repeat in both directions (repeat).
|
background-position | Alignment | Align the background image in the background origin rectangle . The default alignment is upper left corner .
|
background-attachment | Attachment | Set up QAbstractScrollArea Whether the background image in the is scrolled or fixed relative to the viewport . By default , The background image scrolls with the viewport . |
background-clip | Origin | Set how the background color and background image are cut to fill the background rectangle . |
background-origin | Origin | Set the background rectangle of the form , Use with background position and background image . |
border | Border | Set the border properties of the form , Include border-color , border-style and border-width. You can also use border-top、border-left Set the style of each edge of the border independently . for example :QLineEdit { border: 1px solid white } 、QLineEdit { border-right: 1px solid white } |
border-color | Box Colors | Set the color style of the border , It can also be used
|
border-image | Border Image | Use pictures to fill borders . The image is cut into nine parts (top left, top center, top right, center left, center, center right, bottom left, bottom center, and bottom right), And stretch properly if necessary . |
border-radius | Radius | Set the radians of the four corners of the rectangle , You can also use QLineEdit { border-radius: 4px; } |
border-style | Border Style | Set the type of border line , You can also use border-top-style , border-right-style And so on to specify the type of any line . QLineEdit { border-style: solid;} |
border-width | Box Lengths | Set the width of the border line , It can also be used border-top-width , border-right-width Wait to set the width of a specific line . QLineEdit { border-width: 1px;} |
bottom | Length | Set the sub control of the control ( Such as ComboBox The pull-down button ) The location of . If the position is relative ( Default ) Moves the child control up by the specified offset ; If the position is absolute , The distance between the bottom of the child control and the bottom of the parent control . for example :QSpinBox::down-button { bottom: 2px }. It can also be used left、top、right Set other margins between the child control and the parent control . Use height Set the height of the child control . |
color | Brush | Set the color of the text , for example :QPushButton { color: red } |
font | Font | Set text properties , Include font-family( typeface ) , font-size( size ) , font-style( tilt ) and font-weight( In bold ). for example : QCheckBox { font: bold italic large "Times New Roman" } |
gridline-color * | Color | Set up QTableView The color of the middle grid . for example :* { gridline-color: gray } |
icon | Url+ | Set the icon with icon control , At present, the only controls with this property are QPushButton. |
icon-size | Length | Set the length and width of the icon . |
image * | Url+ | The image drawn in the content rectangle of the child control . for example :QSpinBox::down-button { image: url(:/images/spindown.png) } |
lineedit-password-character* | Number | Set up QLineEdit Characters displayed in , You can use Unicode Specifies the character encoding of . for example * { lineedit-password-character: 9679 }, Said the use of Unicode in 9679 The sign character displays . |
lineedit-password-mask-delay* | Number | stay lineedit-password-character Apply before visible characters ,QLineEdit Password mask delay ( In Milliseconds ). for example :* { lineedit-password-mask-delay: 1000 } |
margin | Box Lengths | Set the edge distance between the form and other forms , You can use margin-top , margin-right , margin-bottom , and margin-left To specify the . for example : QLineEdit { margin: 2px } |
padding | Box Lengths | Set the margin between the form and the inner subform , You can also use |
spacing* | Length | Set the margin between internal subforms . for example :QMenuBar { spacing: 10 } |
text-align | Alignment | Set font alignment .QPushButton { text-align: left;} |
The above is just a brief introduction to some common attribute settings , How to set specific attributes? You can view the type of each attribute , Official documents It gives a very detailed way and significance of setting each attribute .
Four 、 Child controls
Qss In addition to common controls 、 Set the style of the form , You can also control its child controls ( Such as QComboBox The pull-down button 、QSpinBox Up and down buttons, etc ) The location of , Fill in the picture and other properties to set . In this case, you can use the control name :: The name of the child control selector. for example :QComboBox::drop-down { image: url(dropdown.png) } Used to set QComboBox Picture of the drop-down button . More child control names are shown in the following table :
5、 ... and 、 Pseudo state
Qt Some controls in have many states , Sometimes it is necessary to distinguish between different states ( For example, the selection of buttons 、 According to the distinction of inferior status ), You need to set different styles for different states . At this time to use Control name : Status name Express selector. for example :QPushButton:hover { color: white } Indicates to set the font color of the button when the mouse is placed on the button . See the following table for more status names :
Pseudo state | explain |
---|---|
:active | The state when the form is an active form |
:adjoins-item | When one QTreeView Of ::branch When adjacent to an item , The status is set . |
:alternate | When QAbstractItemView::alternatingRowColors() Set to true when , draw QAbstractItemView This state is set for each line of the . |
:bottom | Control at the bottom . for example ,QTabBar The label is at the bottom . |
:checked | Select the . for example ,QAbstractButton Selected state of . |
:closable | Projects can be closed . for example ,QDockWidget Open the QDockWidget:: dockwidgetcloseable characteristic . |
:closed | The project is closed . for example ,QTreeView A non expanded item in |
:default | This item is the default . for example , A default QPushButton or QMenu A default action in . |
:disabled | This item is disabled . |
:editable | QComboBox It's editable . |
:edit-focus | The project has editing focus ( see QStyle::State_HasEditFocus). This status only applies to Qt Extend the application . |
:enabled | Enable this . |
:exclusive | The item is part of an exclusive item group . for example , Monopoly QActionGroup Menu items in . |
:first | The project is ( In the list ) The first one is . for example ,QTabBar The first tab in . |
:flat | The project is flat . for example , A flat QPushButton. |
:floatable | Items can float . for example ,QDockWidget To enable the QDockWidget:: dockwidgetfloatatable characteristic . |
:focus | The project has input focus . |
:has-children | The project has subprojects . for example ,QTreeView One of the items in has children . |
:has-siblings | The project has brothers . for example ,QTreeView An entry in . |
:horizontal | The project has a horizontal orientation |
:hover | Hover over the item . |
:indeterminate | The project is in an uncertain state . for example ,QCheckBox or QRadioButton Partially selected . |
:last | This project is ( In the list ) The last project . for example ,QTabBar The last tab in . |
:left | The project is located on the left . for example ,QTabBar The tab for is located on the left . |
:maximized | The project is maximized . for example , To maximize the QMdiSubWindow. |
:middle | The project in ( In the list ) middle . for example , One is not QTabBar Start or end tabs . |
:minimized | Projects are minimized . for example , Minimized QMdiSubWindow. |
:movable | Projects can move around . for example ,QDockWidget To enable the QDockWidget::DockWidgetMovable characteristic . |
:no-frame | The project has no framework . for example , A frameless QSpinBox or QLineEdit. |
:non-exclusive | Items are part of a non exclusive group . for example , Not exclusive QActionGroup Menu items in . |
:off | For items that can be switched , This applies to situations where “ close ” Status items . |
:on | For items that can be switched , This applies to situations where “on” Status widget . |
:only-one | The project is the only ( In the list ). for example ,QTabBar A separate label in . |
:open | The project is open . for example , In a QTreeView Projects expanded in , Or a with an open menu QComboBox or QPushButton. |
:next-selected | Select the next item ( In the list ). for example ,QTabBar The selected tab is next to the item . |
:pressed | The project is using the mouse to press . |
:previous-selected | Select the previous item ( In the list ). for example ,QTabBar The tab in the next to the selected tab . |
:read-only | The item is marked as read-only or non editable . for example , read-only QLineEdit Or non editable QComboBox. |
:right | The project is located on the right . for example ,QTabBar The tabs are located on the right . |
:selected | The item is selected . for example ,QTabBar The selected tab or QMenu Selected item in . |
:top | The project is at the top . for example ,QTabBar The label is on the top . |
:unchecked | Unchecked . |
:vertical | The project has a vertical orientation . |
:window | A widget is a window ( That is, the top-level widget ) |
6、 ... and 、 Conflict handling mechanism
When multiple style rules specify the same attribute with different values , Consider the following style sheets :QPushButton#okButton { color: gray } QPushButton { color: red } . Both of these rules match a rule named okButton Of QPushButton example , And for the color Property conflicts . To solve this conflict , We must consider the particularity of selectors . In the example above ,QPushButton#okButton Considered to be more than QPushButton More specifically , Because it ( Usually ) Reference an object , Instead of all instances of a class .
So when multiple style rules conflict , The system will choose more targeted ( Specificity ) Use the style rules of . And to determine the specificity of the rules ,Qt Style sheets follow CSS2 standard :
The specificity of the selector is calculated as follows :
In the statistics selector ID The number of attributes (= a)
Count the number of other properties and pseudo classes in the selector (= b)
Count the number of element names in the selector (= c)
And then according to a*100+b*10+c Calculate the specificity value of the corresponding rule . The greater the specificity value, the better the matching .
for example :
* {} /* a=0 b=0 c=0 -> specificity = 0 */
LI {} /* a=0 b=0 c=1 -> specificity = 1 */
UL LI {} /* a=0 b=0 c=2 -> specificity = 2 */
UL OL+LI {} /* a=0 b=0 c=3 -> specificity = 3 */
H1 + *[REL=up]{} /* a=0 b=1 c=1 -> specificity = 11 */
UL OL LI.red {} /* a=0 b=1 c=3 -> specificity = 13 */
LI.red.level {} /* a=0 b=2 c=1 -> specificity = 21 */
#x34y {} /* a=1 b=0 c=0 -> specificity = 100 */
7、 ... and 、 Example
The modified example is mainly for Qt Self contained Style sheet Modification of the example .
//.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QMainWindow>
#include <QApplication>
class Widget : public QMainWindow
{
Q_OBJECT
public:
Widget(QMainWindow *parent = nullptr);
~Widget();
};
#endif // WIDGET_H
//.cpp
#include "widget.h"
#include <QFrame>
#include <QLabel>
#include <QComboBox>
#include <QSpinBox>
#include <QLineEdit>
#include <QTextEdit>
#include <QCheckBox>
#include <QRadioButton>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QStringList>
#include <QDialogButtonBox>
#include <QFile>
#include <QMessageBox>
Widget::Widget(QMainWindow *parent)
: QMainWindow(parent)
{
QLabel *label1 = new QLabel(" full name :");
label1->setProperty("class","mandatory");
QComboBox *cmb1 = new QComboBox();
cmb1->setObjectName("name");
cmb1->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); // The default is double Preferred
QLabel *label2 = new QLabel(" Gender :");
QRadioButton *rbtn1 = new QRadioButton(" male ");
QRadioButton *rbtn2 = new QRadioButton(" Woman ");
QHBoxLayout *hlayout1 = new QHBoxLayout();
hlayout1->addWidget(rbtn1);
hlayout1->addWidget(rbtn2);
hlayout1->addStretch(1);
QGroupBox *groupBox = new QGroupBox();
groupBox->setLayout(hlayout1);
QLabel *label3 = new QLabel(" Age :");
QSpinBox *spinBox1 = new QSpinBox();
spinBox1->setValue(22);
spinBox1->setRange(18,45);
spinBox1->setSingleStep(1);
QHBoxLayout *hlayout2 = new QHBoxLayout();
hlayout2->addWidget(spinBox1);
hlayout2->addStretch(1);
QLabel *label4 = new QLabel(" password :");
QLineEdit *lineEdit1 =new QLineEdit("Password");
lineEdit1->setEchoMode(QLineEdit::Password);
QLabel *label5 = new QLabel(" Country :");
QComboBox *cmb2 = new QComboBox();
QStringList str;
str<<" China "<<" Egypt "<<" The French "<<" Germany "<<" Italy "<<" India "<<" The Norwegian "<<" Pakistan ";
cmb2->addItems(str);
cmb2->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
QLabel *label6 = new QLabel(" occupation :");
QTextEdit *textEdit1 = new QTextEdit(" developer ");
textEdit1->append(" Student ");
textEdit1->append(" Entrepreneur ");
textEdit1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
QCheckBox *checkBox = new QCheckBox(" I accept these terms and conditions !");
QDialogButtonBox *dialogBtnBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
QGridLayout *glayout = new QGridLayout();
glayout->addWidget(label1,0,0);
glayout->addWidget(cmb1,0,1);
glayout->addWidget(label2,1,0);
glayout->addWidget(groupBox,1,1);
glayout->addWidget(label3,2,0);
glayout->addLayout(hlayout2,2,1);
glayout->addWidget(label4,3,0);
glayout->addWidget(lineEdit1,3,1);
glayout->addWidget(label5,4,0);
glayout->addWidget(cmb2,4,1);
glayout->addWidget(label6,5,0);
glayout->addWidget(textEdit1,5,1);
glayout->addWidget(checkBox,6,0,1,2);
glayout->addWidget(dialogBtnBox,7,0,1,2);
glayout->setSizeConstraint(QLayout::SetDefaultConstraint);
QString dirPath = QApplication::applicationDirPath();
//QString fileName = dirPath+"/coffee.qss";
QString fileName = "../qss/qss/coffee.qss";
QFile qssFile(fileName);
if(!qssFile.open(QFile::ReadOnly))
{
QMessageBox::warning(this," fail to open file ",fileName+" Open the failure ");
exit(1);
}
QString qssString = qssFile.readAll();
this->setStyleSheet(qssString);
QFrame *mframe = new QFrame();
mframe->setLayout(glayout);
this->setCentralWidget(mframe);
}
Widget::~Widget()
{
}
.qss file
Widget {
background-color: beige;
}
/* Nice Windows-XP-style password character. */
QLineEdit[echoMode="2"] {
lineedit-password-character: 9679;
}
/* We provide a min-width and min-height for push buttons
so that they look elegant regardless of the width of the text. */
QPushButton {
background-color: palegoldenrod;
border-width: 2px;
border-color: darkkhaki;
border-style: solid;
border-radius: 5;
padding: 3px;
min-width: 9ex;
min-height: 2.5ex;
}
QPushButton:hover {
background-color: khaki;
}
/* Increase the padding, so the text is shifted when the button is
pressed. */
QPushButton:pressed {
padding-left: 5px;
padding-top: 5px;
background-color: #d0d67c;
}
QLabel, QAbstractButton {
font: bold;
}
/* Mark mandatory fields with a brownish color. */
.mandatory {
color: brown;
}
/* Bold text on status bar looks awful. */
QStatusBar QLabel {
font: normal;
}
QStatusBar::item {
border-width: 1;
border-color: darkkhaki;
border-style: solid;
border-radius: 2;
}
QComboBox, QLineEdit, QSpinBox, QTextEdit, QListView {
background-color: cornsilk;
selection-color: #0a214c;
selection-background-color: #C19A6B;
}
QComboBox::drop-down#name{
image:url(:/res/drop_down.jpg);
}
QListView {
show-decoration-selected: 1;
}
QListView::item:hover {
background-color: wheat;
}
/* We reserve 1 pixel space in padding. When we get the focus,
we kill the padding and enlarge the border. This makes the items
glow. */
QFrame{
/*background-color: beige;*/
margin:10px;
}
QLineEdit, QFrame {
border-width: 2px;
padding: 1px;
border-style: solid;
border-color: darkkhaki;
border-radius: 5px;
}
/* As mentioned above, eliminate the padding and increase the border. */
QLineEdit:focus, QFrame:focus {
border-width: 3px;
padding: 0px;
}
/* A QLabel is a QFrame ... */
QLabel {
border: none;
padding: 0;
background: none;
}
/* A QToolTip is a QLabel ... */
QToolTip {
border: 2px solid darkkhaki;
padding: 5px;
border-radius: 3px;
opacity: 200;
}
/* Nice to have the background color change when hovered. */
QRadioButton:hover, QCheckBox:hover {
background-color: wheat;
}
/* Force the dialog's buttons to follow the Windows guidelines. */
QDialogButtonBox {
button-layout: 0;
}
design sketch :
边栏推荐
猜你喜欢
第三课threejs全景预览房间案例
HCIA-R&S自用笔记(25)NAT技术背景、NAT类型及配置
[typescript] type reduction (including type protection) and type predicate in typescript
Sqlmap是什么以及使用方法
Clickhouse learning (VIII) materialized view
table中同一列中合并相同项
解决表单校验提示信息不消失问题以及赋值不生效问题
Three handshakes and four waves for the interview summary
微信小程序-屏幕高度
【TypeScript】深入学习TypeScript对象类型
随机推荐
微信小程序-组件传参,状态管理
Sqlmap是什么以及使用方法
Hcia-r & s self use notes (24) ACL
个人学习笔记
href与src的区别
C language file operation
WIN10 编译ffmpeg(包含ffplay)
Flask 报错 RuntimeError: The session is unavailable because no secret key was set.
Cmu15-213 shell lab experiment record
Playwright实战案例之爬取js加密数据
[C language series] - realize the exchange of two numbers without creating the third variable
Clickhouse learning (IX) Clickhouse integrating MySQL
Installation steps and environment configuration of vs Code
uniapp组件之选择选项(如套餐选择)
Merge the same items in the same column in table
OpenAtom OpenHarmony分论坛圆满举办,生态与产业发展迈向新征程
Masscan使用教程.
Clickhouse learning (V) cluster operation
弹性盒子相关知识
Day 1