Style sheets 是由一系列的style rules组成的。一条style rule 由选择器selector和声明declaration这两部分构成。selector说明这条规则在哪些widgets上起作用,declaration说明要在这些widgets上设置什么属性properties。例如:
QPushButton, QLineEdit { color: red; background-color: white }
在上面这条style rule中QPushButton, QLineEdit 是两个选择器,中间用逗号连接。 { color: red; background-color: white }是声明declaration,大括号里面是一系列的 property: value对,中间用分号连接。这条规则指出对QPushButton和QLineEdit 以及他们的子类需要使用红色作为其前景色,并使用白色作为其背景色。
如果控件较多或比较复杂,我们可以通过使用qss文件来设置Style Sheet。首先我们新建一个文本文档,后缀名改为qss,然后用文本编辑器比如记事本打开它,将我们设置的Style Sheets写进去然后保存就可以了。本例程创建的qss文件叫stylesheetDemo.qss,于是我们在程序中只需要写如下几行代码就可以使我们写在qss文件中的Style Sheets起作用:
QFile file(":/qss/stylesheetDemo.qss");
file.open(QFile::ReadOnly);
QTextStream filetext(&file);
QString stylesheet = filetext.readAll();
ui->tab->setStyleSheet(stylesheet);
程序中stylesheetDemo.qss已加入到资源文件,其中ui->tab就是TabWidget中的第一个tab页面。
qss文件中常见设置:
QGroupBox {
background-image: url(:/pics/background.png);
border-radius: 30px;
}
QLabel {
color: gray;
}
QLineEdit {
background: qradialgradient(cx:0, cy:0, radius: 1,
fx:0.5, fy:0.5, stop:0 white, stop:1 rgba(0,190,0, 60%));
border-radius: 9px;
}
QCheckBox:checked {
color: green;
}
QCheckBox::indicator {
width: 25px;
height: 25px;
}
QCheckBox::indicator:checked {
image: url(:/pics/checkbox.gif);
}
QRadioButton{
spacing: 10
}
QRadioButton::indicator {
width: 25px;
height: 25px;
}
QRadioButton:checked {
color: rgb(230,115, 0);
}
QRadioButton::indicator:checked {
image: url(:/pics/radioButton.png);
}
QPushButton{
text-align: right;
}