本文借用HTML的css语法,将样式表应用到窗口部件。这里只是个简单的例子,实际上样式表的语法很丰富。
以下类似于css:
StyleSheet = """
QComboBox { color: darkblue; }
QLineEdit { color: darkgreen; }
QLineEdit[mandatory="true"] { #mandatory="true"时,QLineEdit的样式会变化
background-color: rgb(255, 255, 127);
color: darkblue;
}
如果在选择器的前面加上一个句点,比如.QLineEdit,则选择器就会只应用于指定的类,而不会应用于这个类的子类。如果要求选择器仅用于某一特定窗口部件,则可以对该窗口部件调用setObjectName(),然后用该名字作为选择器的一部分。比如,如果有一个按钮,其对象名字是“findButton”,则应用于这个按钮的选择器就应该是QpushButton#findButton。有些窗口部件会有一些子控件。例如QComboBox会有一个箭头子控件,用户通过点击这个箭头来看到下拉列表。子控件可以指定为选择器的一部分–例如,QComboBox::drop-down。伪状态可以用一个冒号指定–例如,QCheckBox::checked.
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,
QDialogButtonBox, QGridLayout, QLabel, QLineEdit, QVBoxLayout)
class ContactDlg(QDialog):
StyleSheet = """
QComboBox { color: darkblue; }
QLineEdit { color: darkgreen; }
QLineEdit[mandatory="true"] {
background-color: rgb(255, 255, 127);
color: darkblue;
}
"""
def __init__(self, parent=None):
super(ContactDlg, self).__init__(parent)
forenameLabel =