QT for PYthon PySide6 GUI界面开发实例与详解 Demo2_4.py 代码报错
执行到
palette = label.palette()
palette.setColor(palette.Active,palette.window,colorBase)
palette.setColor(palette.Active,palette.windowText,colorText)
代码报错 AttributeError: ‘PySide6.QtGui.QPalette’ object has no attribute ‘Active’
正确代码是
palette = label.palette() #注释掉该行,取消下行注释 也可正确运行
#palette =QPalette()
palette.setColor(QPalette.ColorRole.Window,colorBase)
palette.setColor(QPalette.ColorRole.WindowText,colorText)
或
palette =QPalette() #注释掉该行,取消下行注释,也可正确运行
#palette = label.palette()
palette.setColor(QPalette.ColorGroup.Active,QPalette.ColorRole.Window,colorBase)
palette.setColor(QPalette.ColorGroup.Active,QPalette.ColorRole.WindowText,colorText)
全部代码如下:
#Demo2_4.py
#调色板类QPalette的应用实例
#该程序在窗品上设置10个标签,然后给每个标签的背景和前景随机设置不同的颜色,并获取背景和前景颜色值,将其RGB值显示在标签上
import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication,QWidget,QLabel
from PySide6.QtGui import QFont,QColor ,QPalette
from random import randint,seed
class SetPalette(QWidget):
def __init__(self, parent = None):
super().__init__(parent)
self.setGeometry(200,200,1200,500) #设置窗口尺寸
self.setWindowTitle("设置调色版实例")
self.createLabels()
self.setLabelColor()
self.getLabelColorRGB()
def createLabels(self):
self.labels =list()
font = QFont("黑体",pointSize=20)
string = "Nice to meet you! 很高兴认识你!"
for i in range(10):
label = QLabel(self)
label.setGeometry(5,50*i,1200,40)
label.setText(str(i) + ":" + string)
label.setFont(font)
self.labels.append(label)
def setLabelColor(self):
seed(12)
for label in self.labels:
colorBase = QColor(randint(0,255),randint(0,255),randint(0,255))
colorText = QColor(randint(0,255),randint(0,255),randint(0,255))
#报错
# palette = label.palette()
# palette.setColor(palette.Active,palette.window,colorBase)
# palette.setColor(palette.Active,palette.windowText,colorText)
#正确方法1
#palette = label.palette()
palette =QPalette()
palette.setColor(QPalette.ColorRole.Window,colorBase)
palette.setColor(QPalette.ColorRole.WindowText,colorText)
#正确方法2
# palette =QPalette()
# palette = label.palette()
# palette.setColor(QPalette.ColorGroup.Active,QPalette.ColorRole.Window,colorBase)
# palette.setColor(QPalette.ColorGroup.Active,QPalette.ColorRole.WindowText,colorText)
label.setAutoFillBackground(True)
label.setPalette(palette)
def getLabelColorRGB(self):
for label in self.labels:
r,g,b,a = label.palette().window().color().getRgb()
rT,gT,bT,a = label.palette().windowText().color().getRgb()
text = (label.text() + "背景颜色:{}{}{} 文字颜色{}{}{}").format(r,g,b,rT,gT,bT)
label.setText(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = SetPalette()
window.show()
sys.exit(app.exec())