一.QSS基础
QSS (Qt Style Sheets)
Qt样式表
用于设置控件的样式
代码:
from PyQt5.QtWidgets import *
import sys
class BasicQSS(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QSS样式")
btn1 = QPushButton(self)
btn1.setText("按钮1")
btn2 = QPushButton(self)
btn2.setText("按钮2")
btn3 = QPushButton(self)
btn3.setText("按钮3")
vbox = QVBoxLayout()
vbox.addWidget(btn1)
vbox.addWidget(btn2)
vbox.addWidget(btn3)
self.setLayout(vbox)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = BasicQSS()
# 选择器
#所有的QPushButton控件都设置为背景颜色为红色
qssStyle = '''
QPushButton {
background-color:red
}
'''
form.setStyleSheet(qssStyle)
form.show()
sys.exit(app.exec_())
运行结果:
二.使用QSS选择器设置控件样式
代码:
from PyQt5.QtWidgets import *
import sys
class QSSSelector(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QSS样式")
btn1 = QPushButton(self)
btn1.setText("按钮1")
btn2 = QPushButton(self)
#设置name属性,可根据属性来指定按钮
btn2.setProperty('name','btn2')
btn2.setText("按钮2")
btn3 = QPushButton(self)
btn3.setProperty('name','btn3')
btn3.setText("按钮3")
vbox = QVBoxLayout()
vbox.addWidget(btn1)
vbox.addWidget(btn2)
vbox.addWidget(btn3)
self.setLayout(vbox)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = QSSSelector()
# 选择器
#指定按钮
qssStyle = '''
QPushButton[name="btn2"] {
background-color:red;
color:yellow;
height:120;
font-size:60px;
}
QPushButton[name="btn3"] {
background-color:blue;
color:yellow;
height:60;
font-size:30px;
}
'''
form.setStyleSheet(qssStyle)
form.show()
sys.exit(app.exec_())
运行结果:
三.QSS子控件选择器
代码:
from PyQt5.QtWidgets import *
import sys
class QSSSubControl(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QSS子控件选择器")
combo = QComboBox(self)
#设置下拉框名字
combo.setObjectName("myComboBox")
combo.addItem("Window")
combo.addItem("Linux")
combo.addItem("Mac OS X")
combo.move(50,50)
self.setGeometry(250,200,320,150)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = QSSSubControl()
'''
通过名字来引用,#myComboBox相当于web里通过id来引用
drop-down是下拉子控件
'''
qssStyle = '''
QComboBox#myComboBox::drop-down {
image:url(../picture/icon/first.png)
}
'''
form.setStyleSheet(qssStyle)
form.show()
sys.exit(app.exec_())
运行结果: