我遇到了一些奇怪的行为,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()在开头是相同的对象,为什么它们在结尾不再相同?这里发生什么事情?我很困惑。谢谢。
发布于 2012-03-01 06:43:57
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)你应该会得到你想要的结果。
https://stackoverflow.com/questions/9507809
复制相似问题