QML Opacity Inheritance

前端 未结 9 1935
刺人心
刺人心 2020-12-31 04:12

In QML, how can I prevent a child element from inheriting the opacity from its parent? I want to set different opacity values for the parent and it\'s child element.

相关标签:
9条回答
  • 2020-12-31 04:47

    Actually, setting layer.enabled: true for the parent element does the thing for me. The whole element is rendered to the buffer, and opacity is applied to the resulting buffer (to the whole layer at once).

    See http://doc.qt.io/qt-5/qml-qtquick-item.html#layer.enabled-prop

    Example code:

    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'
        }
    }
    

    That is a solution, but make sure that you know what you are doing when enabling layering.

    Another possible solution would be using a shadereffect.

    Thanks to peppe on #qt@freenode.

    0 讨论(0)
  • 2020-12-31 04:48

    You can't. Items opacity value is relative to their parents one, so if you code something like

    Rectangle {
      color: "red"
      opacity: 0.5
      width: 200; height: 100
    
      Rectangle {
        color: "blue"
        opacity: 1
        width: 100; height: 100
      }
    }
    

    You will see that the two rectangles have the same opacity.

    0 讨论(0)
  • 2020-12-31 04:48

    You cannot prevent the child element from inheriting the opacity from its parent.

    My personal work around is to change this:

    Rectangle {
        color: "red"
        opacity: 0.5
        width: 200; height: 100
    
        Rectangle {
            color: "blue"
            opacity: 1
            width: 100; height: 100
        }
    }
    

    Into this:

    Item {
        width: 200; height: 100
    
        Rectangle {
            anchors.fill: parent
            color: "red"
            opacity: 0.5
        }
    
        Rectangle {
            color: "blue"
            opacity: 1
            width: 100; height: 100
        }
    
    }
    

    or this (only possible if the parent is a solid color):

    Rectangle {
        color: "#7FFF0000" // 50% transparent red
        opacity: 0.5
        width: 200; height: 100
    
        Rectangle {
            color: "blue"
            opacity: 1
            width: 100; height: 100
        }
    }
    
    0 讨论(0)
提交回复
热议问题