import sys
from PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout, QPushButton, QComboBox, QStyleOption, QStyle
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeyEvent, QIcon, QPixmap, QPaintEvent, QPainter
class QSSSelector(QWidget):
def __init__(self):
super(QSSSelector, self).__init__()
self.setWindowTitle("窗口最大化和最小化")
self.resize(500, 500)
self.setProperty("name", "widget")
self.button1 = QPushButton("按钮1")
self.button2 = QPushButton("按钮2")
self.button2.setProperty("name", "btn2") # 设置的属性是以键值对方式
self.button3 = QPushButton("按钮3")
self.button3.setProperty("name", "btn3")
self.comboBox = QComboBox()
self.comboBox.setObjectName("cb") # 设置对象名字
self.comboBox.addItems(["windows", "macOS", "linux"])
self.vLayout = QVBoxLayout(self)
self.vLayout.addWidget(self.button1)
self.vLayout.addWidget(self.button2)
self.vLayout.addWidget(self.button3)
self.vLayout.addWidget(self.comboBox)
# 打开qss文件
with open(r"style sheet.qss", "r", encoding="utf-8") as file:
qss = file.read()
print(qss)
# # 选择器,将所有的PushButton背景改为红色
self.setStyleSheet(qss)
def paintEvent(self, a0: QPaintEvent) -> None: # 设置父窗口背景图时,需要重写paintEvent方法。如果是QMainWidow时不需要。
opt = QStyleOption()
opt.initFrom(self)
painter = QPainter(self)
# painter.setRenderHint(QtGui.QPainter.Antialiasing) # 反锯齿
self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QSSSelector()
window.show()
sys.exit(app.exec_())
.QSS文件内容:
QPushButton{
background-color: red;
}
QPushButton[name="btn2"]{
background-color: rgb(100, 50, 50,50);
color: blue;
height: 60;
font-size: 30px;
}
QComboBox#cb::drop-down {
image: url(./images/2.png);
}
QWidget[name="widget"]{
background-image: url(images/blue.png);
}
|