如何使用类更好地设置此应用的样式,而不是为每个应该看起来相同的标签重新定义相同的样式。这使得改变样式变得很痛苦,因为我必须遍历每个看起来相同的标签并粘贴代码才能匹配。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
#Add all GUI Elements to Class
self.amountLabel = QtGui.QLabel('Amount')
self.counterLabel = QtGui.QLabel('Counter')
self.totalLabel = QtGui.QLabel('Total')
self.amountSpin = QtGui.QSpinBox()
self.counterSpin = QtGui.QSpinBox()
self.totalOutput = QtGui.QLabel('0')
grid = QtGui.QGridLayout()
grid.setSpacing(0)
grid.addWidget(self.amountLabel, 3, 0)
grid.addWidget(self.counterLabel, 3, 1)
grid.addWidget(self.totalLabel, 3, 2)
grid.addWidget(self.amountSpin, 4, 0)
grid.addWidget(self.counterSpin, 4, 1)
grid.addWidget(self.totalOutput, 4, 2)
self.setLayout(grid)
# STYLING
self.amountLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); }")
self.amountSpin.setStyleSheet("QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
self.counterLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); }")
self.counterSpin.setStyleSheet("QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
self.totalLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-weight:bold; font-size: 11px; background-color: rgba(26, 188, 182, 150); border: 1px solid rgba(26, 188, 182, 255); }")
self.totalOutput.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-weight:bold; font-size: 11px; background-color: rgba(26, 188, 182, 50); border: 1px solid rgba(26, 188, 182, 255); }")
self.setGeometry(800, 400, 250, 80)
self.setWindowTitle('Simple Calculator')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:5)
如果我没有弄错,父母的样式表将应用于所有孩子,除非被覆盖。
你可以试试这个:
# STYLING
self.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); } QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
#setting CS of self (the widget) and not the children
self.setGeometry(800, 400, 250, 80)
self.setWindowTitle('Simple Calculator')
self.show()
关于你的不同按钮:
label1.setProperty('labelClass', 'red')
label2.setProperty('labelClass', 'blue')
并在小部件的CS中:
QLabel[labelClass="red"] {...}
QLabel[labelClass="blue"] {...}