QSS
QSS(Qt Style Sheets)即PyQt樣式表,是用來定義控件外觀的一種機制。QSS內部實現大量參考了CSS,但是功能沒有CSS強大,主要體現在選擇器少,屬性少等。
使用QSS
格式:控件.setStyleSheet(str)
說明:str表示QSS樣式
例子:button.setStyleSheets('background-color: red')
QSS語法
基本規則
QSS文件由一系列的“屬性:值”對,使用分號間隔,使用大括號將聲明包括在內。
選擇器
通配選擇器:*,匹配所有的控件
類型選擇器:QPushButton,匹配所有QPushButton類及其子類
屬性選擇器:QPushButton[name='myButton'],匹配所有name是myButton的QPushButton實例,匹配的屬性可以是自定義屬性
類選擇器:.QPushButton,匹配所有QPushButton類實例,但是不匹配子類
ID選擇器:#myButton,匹配所有ID是myButton的控件,ID指的是objectName,通過setObjectName方法設置
后代選擇器:QDialog QPushButton,匹配QDialog中包含的QPushButton,不論是直接還是間接包含
子選擇器:QDialog > QPushButton,匹配QDialog中包含的QPushButton,要求QPushButton的直接父容器時QDialog
子控件
子控件實際上也是一種選擇器,主要應用在復合組件上,典型的就是QComboBox控件,如指定QComboBox中的下拉箭頭為指定圖片:
QComboBox::drop-down { image : url(xxx.png) }
偽狀態
QSS偽狀態是以冒汗開頭的一個選擇表達式,如:hover表示鼠標滑過時的狀態。常用的偽狀態有:hover checked
例子:設置按鈕的背景為不同顏色
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton styleSheet = ''' #one { background-color: red } #two { background-color: green } ''' class MyWidget(QWidget): def __init__(self): super(MyWidget, self).__init__() self.button1 = QPushButton(self) self.button1.setText('點我1') self.button1.resize(100, 40) self.button1.move(20, 20) self.button1.setObjectName('one') self.button2 = QPushButton(self) self.button2.setText('點我2') self.button2.resize(100, 40) self.button2.move(20, 80) self.button2.setObjectName('two') if __name__ == '__main__': app = QApplication(sys.argv) w = MyWidget() w.setStyleSheet(styleSheet) w.resize(500, 300) w.move(300, 300) w.setWindowTitle('Simple') w.show() sys.exit(app.exec_())
注:除了自己編寫樣式外,網上有很多質量非常高的QSS樣式,直接瀏覽下載就OK。