我正在使用pyqt 4.11并尝试使用循环创建一组标签,并希望更改每个Label的颜色。但是,颜色仍然是默认的黑色。
red = (255,0,0)
orange = (255,128,0)
yellow = (255,255,0)
green = (0,255,0)
loop = 0
NAME = ["apple","banana","strawberry","orange"]
NAME_COLOR = [green,yellow,red,orange]
while loop < len(NAME):
lbl = QtGui.QLabel(self)
lbl.setText(NAME[loop])
lbl.move(loop*50,120)
lbl.setStyleSheet('QLabel { color: NAME_COLOR[loop]}')
lbl.show()
loop = loop + 1
答案 0 :(得分:1)
要设置标签的颜色,您需要使用setStyleSheet
,如下所示:
lbl.setStyleSheet('color: rgb{}'.format("(255,128,0)"))
以下是使用 PyQt4 的程序的工作示例:
from PyQt4 import QtGui
red = (255, 0, 0)
orange = (255, 128, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
layout = QtGui.QVBoxLayout()
name = ["apple", "banana", "strawberry", "orange"]
name_color = [green, yellow, red, orange]
_dict = dict(zip(name, name_color))
# _dict = {'apple': (0, 255, 0), 'banana': (255, 255, 0),
# 'orange': (255, 128, 0), 'strawberry': (255, 0, 0)}
for name, color in _dict.items():
label = QtGui.QLabel(self)
label.setText(name)
label.setStyleSheet('color: rgb{}'.format(str(color)))
layout.addWidget(label)
self.setLayout(layout)
if __name__ == '__main__':
app = QtGui.QApplication([])
w = Window()
w.show()
app.exec_()
结果: