如何使用qt-component OpacityMask

时间:2017-12-20 05:30:15

标签: qt qml qt-quick

有一个问题How to hide an image using transparent rectangle in QML?

接受的答案是使用OpacityMask 我按照这个答案创建了一个qml文件,但没有得到预期的结果 我的代码有什么问题吗?

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtGraphicalEffects 1.0

ApplicationWindow {
    visible: true
    width: 1280
    height: 800
    title: qsTr("Hello World")

    Rectangle {
        id: background
        anchors.fill: parent
        color: "black"
    }

    Image
    {
        id:underlyingImage
        width: 1204
        height: 682

        fillMode: Image.PreserveAspectCrop
        layer.enabled: true
        layer.effect: OpacityMask {
            maskSource: hiding_rect
        }

        source:"qrc:/timg.jpg"
    }
    Rectangle
    {
        id:hiding_rect
        width: underlyingImage.width/2
        height: underlyingImage.height/2
        color: "yellow"
    }
}

the result picture

1 个答案:

答案 0 :(得分:0)

我不熟悉其他问题中建议的方法。 但是,按照文档(http://doc.qt.io/qt-5/qml-qtgraphicaleffects-opacitymask.html)中建议的方法,这可行:

Window {
    visible: true
    width: 1280
    height: 800
    title: qsTr("Hello World")

    Rectangle {
        id: background
        anchors.fill: parent
        color: "black"
    }

    Image
    {

        anchors.centerIn: parent

        id:underlyingImage
        width: 1204
        height: 682

        fillMode: Image.PreserveAspectCrop
        source:"file:///tmp/timg.jpg"
        visible: false
    }

    Item {
        id:hiding_rect
        anchors.fill: underlyingImage
        visible: false
        Rectangle
        {
            anchors.left: parent.left
            anchors.top: parent.top
            width: underlyingImage.width/2
            height: underlyingImage.height/2
            color: Qt.rgba(1,1,1,1)
            z: underlyingImage.z + 1
        }
    }




    OpacityMask {
        anchors.fill: underlyingImage
        source: underlyingImage
        maskSource: hiding_rect
    }
}