gpt4 book ai didi

python - PyQt QColor setAlpha 不工作?

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:14 25 4
gpt4 key购买 nike

我遇到了奇怪的行为,其中 setAlpha 不在 QColor 对象上工作。我不明白为什么它不起作用,但我确信有一个我还不知道的充分理由。

这是一个小规模示例中的问题:

from PyQt4 import QtGui

clr = QtGui.QColor('yellow')
qtwi = QtGui.QTableWidgetItem()
qtwi.setBackgroundColor(clr)

print 'Colors are the same object: %s' % (clr == qtwi.backgroundColor())

print 'Alpha before is: %s' % clr.alpha()
clr.setAlpha(67)
print 'Alpha after is: %s' % clr.alpha()

print 'Alpha before is: %s' % qtwi.backgroundColor().alpha()
qtwi.backgroundColor().setAlpha(171)
print 'Alpha after is: %s' % qtwi.backgroundColor().alpha()

print 'Colors are the same object: %s' % (clr == qtwi.backgroundColor())

结果应该是:

Colors are the same object: True
Alpha before is: 255
Alpha after is: 67
Alpha before is: 255
Alpha after is: 255
Colors are the same object: False

这对我来说毫无意义。我在示例的第二部分显然将 alpha 值设置为 171,为什么它不起作用?此外,如果 clr 和 qtwi.backgroundColor() 开始时是同一个对象,为什么最后它们不再相同?这里发生了什么?我很困惑。谢谢。

最佳答案

qtwi.backgroundColor() 返回相同颜色的唯一实例。如果您更改其中一个实例,它不会更改原始颜色。

如果你运行:

print qtwi.backgroundColor()
print qtwi.backgroundColor()

您将获得:

<PyQt4.QtGui.QColor object at 0x7f02c61f9ad0>
<PyQt4.QtGui.QColor object at 0x7f02c61f9a60>

它们是两个不同的对象。它们是原件的副本。如果您更改副本,它不会更改原件。

但是,如果您将 qtwi.backgroundColor() 设置为变量,您的代码将起作用。如果您尝试:

from PyQt4 import QtGui

clr = QtGui.QColor('yellow')
qtwi = QtGui.QTableWidgetItem()
qtwi.setBackgroundColor(clr)

print 'Colors are the same object: %s' % (clr == qtwi.backgroundColor())

print 'Alpha before is: %s' % clr.alpha()
clr.setAlpha(67)
print 'Alpha after is: %s' % clr.alpha()

qtwibg = qtwi.backgroundColor()
print 'Alpha before is: %s' % qtwibg.alpha()
qtwibg.setAlpha(171)
print 'Alpha after is: %s' % qtwibg.alpha()

print 'Colors are the same object: %s' % (clr == qtwibg)

您应该会得到想要的结果。

关于python - PyQt QColor setAlpha 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com