首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PyQt QColor setAlpha不工作吗?

PyQt QColor setAlpha不工作吗?
EN

Stack Overflow用户
提问于 2012-03-01 06:40:21
回答 1查看 2.1K关注 0票数 2

我遇到了一些奇怪的行为,setAlpha没有在QColor对象上工作。我不明白为什么它不工作,但我相信有一个很好的原因,我只是还没有意识到。

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

代码语言:javascript
复制
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())

结果应为:

代码语言:javascript
复制
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()在开头是相同的对象,为什么它们在结尾不再相同?这里发生什么事情?我很困惑。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-01 06:43:57

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

如果您运行以下命令:

代码语言:javascript
复制
print qtwi.backgroundColor()
print qtwi.backgroundColor()

您将获得:

代码语言:javascript
复制
<PyQt4.QtGui.QColor object at 0x7f02c61f9ad0>
<PyQt4.QtGui.QColor object at 0x7f02c61f9a60>

它们是两个不同的物体。它们是原件的复制品。如果更改副本,则不会更改原始副本。

但是,如果将qtwi.backgroundColor()设置为变量,则代码将正常工作。如果你尝试:

代码语言:javascript
复制
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)

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9507809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档