Archived:使用样式表自定义外观
文章信息
Contents |
引言
在某些情况下,我们可能需要修改QT内置窗口部件的外观。从QT 4.2开始,可以使用QT样式表,这是一种从HTML CSS获得灵感的机制。样式表是一种运行时解释的普通文本文件,使用它们不需要任何编程知识。
预备知识
Style sheets 是由一系列的style rules组成的。一条style rule 由选择器selector和声明declaration这两部分构成。selector说明这条规则在哪些widgets上起作 用,declaration说明要在这些widgets上设置什么属性properties。例如
QPushButton, QLineEdit { color: red; background-color: white }上面的代码定义了控件的前景色和背景色。式表是文本规格的,你可以使用 QApplication::setStyleSheet() 作用于整个应用上,代码如下:
qApp->setStyleSheet("QLineEdit{background_color: yellow:}}也可以使用 QWidget::setStyleSheet() 作用于一个特别的窗口上(和他的后代)。代码如下
dialog->setStyleSheet("QLineEdit{background_color: yellow:})如果直接在QLineEdit上设置样式表,可以忽略QLineEdit选择器以及大括号
lineEdit->setStyleSheet("background-color:yellow;");代码示例
下面我们将以一段代码解释如何定义比较复杂的样式,为了便于对代码的理解,我们先展示一下代码的运行效果
对话框的背景图片使用以下的规则设置:
QDialog {
background-image: url(:/images/background.png);
}下面的规则集为这些LABEL设置了COLOR和FONT属性
QLabel {
font: 9pt;
color: rgb(0, 0, 127);
}下面的规则集定义对话框中的QLineEdit和QListView的外观
QLineEdit,
QListView {
color: rgb(127, 0, 63);
background-color: rgb(255, 255, 241);
selection-color: white;
selection-background-color: rgb(191, 31, 127);
border: 2px groove gray;
border-radius: 10px;
padding: 2px 4px;
}
对于QPushButton的定制,我们将使用一种完全不同的方式。用一个准备好的图像作为背景,为了使按钮可以缩放,按钮的背景使用CSS的边界图机制定义
QPushButton {
color: white;
font: bold 10pt;
border-image: url(:/images/button.png) 16;
border-width: 16px;
padding: -16px 0px;
min-height: 32px;
min-width: 60px;
}当鼠标位于QPushButton上方时,我们使用一个更为明亮的图像作为边界图,使其具有更好的悬停效果
QPushButton:hover {
border-image: url(:/images/button-hover.png) 16;
}当用户单击时,可以把前景色改为浅灰色,使用一个暗色的边界图,并把按钮中的文字下移一个像素
QPushButton:pressed {
color: lightgray;
border-image: url(:/images/button-pressed.png) 16;
padding-top: -15px;
padding-bottom: -17px;
}最后的风格规则是自定义QCombox的外观,只读组合框是一个右边带下拉箭头的QPushButton,可编辑的组合框是由一个类似QLineEdit的组件及一个小按钮组成,定义QLineEdit的规则可以用来定义可编辑的组合框
QComboBox:!editable,
QPushButton {
color: white;
font: bold 10pt;
border-image: url(:/images/button.png) 16;
border-width: 16px;
padding: -16px 0px;
min-height: 32px;
min-width: 60px;
}
定义QPushButton的普通规则可以扩展到只读组合框
<code>
QComboBox:!editable,
QPushButton {
color: white;
font: bold 10pt;
border-image: url(:/images/button.png) 16;
border-width: 16px;
padding: -16px 0px;
min-height: 32px;
min-width: 60px;
}
鼠标在只读组合框或则下拉按钮上悬停的规制可以修改背景图片
QComboBox:!editable:hover,
QComboBox::drop-down:editable:hover,
QPushButton:hover {
border-image: url(:/images/butto
}
点击一个按钮如同点击一个QPushButton
QComboBox:!editable:on,
QPushButton:pressed {
color: lightgray;
border-image: url(:/images/button-pressed.png) 16;
padding-top: -15px;
padding-bottom: -17px;
}
定义自己的下拉箭头
QComboBox::down-arrow {
image: url(:/images/down-arrow.png);
}对于可编辑组合框,需要配置下拉按钮,使它看起象个微型按钮
QComboBox::drop-down:editable {
border-image: url(:/images/button.png) 16;
border-width: 10px;
subcontrol-origin: margin;
subcontrol-position: center right;
width: 7px;
height: 6px;
}这样我们就完成了样式表的创建,具体代码参考代码示例


(no comments yet)