在QML中,我如何防止子元素继承其父元素的不透明度?我想要为父元素和其子元素设置不同的不透明度值。
我认为,一种方法是使用半透明颜色,如此处所述,而不是使用不透明度。
例如,使用四元色代码 #800000FF
来表示半透明蓝色。
layer.enabled: true
设置为真即可实现此功能。整个元素将被渲染到缓冲区,并将opacity
应用于生成的缓冲区(整个图层一次性应用)。Rectangle {
width: 400
height: 200
opacity: 0.5
layer.enabled: true
Rectangle {
width: parent.width
height: parent.height
color: 'red'
}
Rectangle {
width: parent.width / 2
height: parent.height
color: 'blue'
}
}
那是一个解决方案,但在启用图层时,请确保知道自己在做什么。
另一个可能的解决方案是使用着色器效果。
感谢 #qt@freenode 上的 peppe。
layers.enabled
控制每个项的 alpha 混合。 - Mohammad Kanan您不能这样做。元素的不透明度值是相对于其父级元素的,因此如果您编写类似以下代码的内容:
Rectangle {
color: "red"
opacity: 0.5
width: 200; height: 100
Rectangle {
color: "blue"
opacity: 1
width: 100; height: 100
}
}
你会发现这两个矩形具有相同的不透明度。
我刚刚遇到了这个问题。使用的是Qt 5.1.0。
在我的情况下,我有一个Rectangle
元素,它具有opacity: 0.6
和一个子Image
元素。 Image
继承了透明度 - 这是不期望的。
为了解决这个问题,我将主要的Rectangle
封装在一个Item
元素中。从Rectangle
传递大小/位置定义到外部Item
。将Image
移到Rectangle
之外。
最后,我有Item
作为主要父级,Rectangle
和Image
并排在Item
内。
只有Rectangle
维持了不透明度0.6,因此Rectangle
具有透明度,而Image
是完全不透明的。
这是可能的!你需要在Component.onCompleted
作用域中测试父级的不透明度。如果它为0,则需要将您的对象的父级更改为当前父级的父级。
示例:
Item{
id:root
Item{
id:currentParent
opacity: 0
Item{
id:item
Component.onCompleted:{
if(parent.opacity === 0)
item.parent = currentParent.parent
}
}
}
}
您无法阻止子元素从其父元素继承不透明度。
我的个人解决方法是更改这个:
Rectangle {
color: "red"
opacity: 0.5
width: 200; height: 100
Rectangle {
color: "blue"
opacity: 1
width: 100; height: 100
}
}
转化为:
Item {
width: 200; height: 100
Rectangle {
anchors.fill: parent
color: "red"
opacity: 0.5
}
Rectangle {
color: "blue"
opacity: 1
width: 100; height: 100
}
}
Rectangle {
color: "#7FFF0000" // 50% transparent red
opacity: 0.5
width: 200; height: 100
Rectangle {
color: "blue"
opacity: 1
width: 100; height: 100
}
}
无法实现此操作,但可以使用Qt.lighter(color,opacity)
更改颜色。
例如:
Rectangle {
color: Qt.lighter("red",.5)
width: 200; height: 100
Rectangle {
color: Qt.lighter("blue",1)
width: 100; height: 100
}
}
Rectangle {
width: 400
height: 400
color: Qt.rgba(0, 0, 0, 0.2) // Works perfectly, pure black with 20% transparency, equal to 0.2 opacity
// Unaffacted child elements here...
}
color: "#000000FA" // Supposed to be semi transparent, but always transparent, regardless of the alpha value
设置任何其他RGBA值的alpha值都可以正常工作,但对于纯黑色却不行。
#FA000000
,它就可以工作了。 - mchiasson