【发布时间】:2012-03-01 12:46:00
【问题描述】:
在 QML 中,如何防止子元素从其父元素继承不透明度? 我想为父元素和它的子元素设置不同的不透明度值。
【问题讨论】:
在 QML 中,如何防止子元素从其父元素继承不透明度? 我想为父元素和它的子元素设置不同的不透明度值。
【问题讨论】:
我认为这是不可能的。您必须使两个元素同级并根据需要更改其不透明度。
【讨论】:
你不能。项目的不透明度值是相对于他们的父母的,所以如果你编写类似的代码
Rectangle {
color: "red"
opacity: 0.5
width: 200; height: 100
Rectangle {
color: "blue"
opacity: 1
width: 100; height: 100
}
}
您会看到两个矩形具有相同的不透明度。
【讨论】:
我认为,一种方法是使用here 所述的半透明颜色,而不是不透明度。
例如使用像 #800000FF 这样的四色代码来表示半透明的蓝色。
【讨论】:
我刚才碰到了这个问题。使用 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 完全不透明。
【讨论】:
实际上,为父元素设置layer.enabled: true 对我来说是这样的。
整个元素被渲染到缓冲区,opacity 被应用到生成的缓冲区(一次应用到整个层)。
见http://doc.qt.io/qt-5/qml-qtquick-item.html#layer.enabled-prop
示例代码:
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 混合
我在 Qt 4.8.6 中也遇到过这个问题。
在我的特定情况下,我希望顶级项目是 20% 透明的黑色,但其子元素不受父项的任何不透明度/透明度设置的影响。
由于 QML 的继承机制,不透明度不起作用。
但我能够使用 Qml Qt 对象中的 rgba 函数。这让我得到了我想要的东西,父元素现在是 20% 透明的,但子元素不受影响。
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...
}
注意:我也尝试过直接使用 RGBA 颜色代码,如之前的海报所述,但它不起作用。
例子:
color: "#000000FA" // Supposed to be semi transparent, but always transparent, regardless of the alpha value
为任何其他 RGBA 值设置 alpha 值都有效,只是不适用于纯黑色。
【讨论】:
#FA000000,它将起作用。
有可能!您需要在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
}
}
【讨论】: