Search code examples
qtqmlcustom-componentdropshadow

Custom Component for DropShadow


Since these properties of DropShadow don't change:

radius: 10
samples: 15
color: "black"

in my usage, I tried to create a Custom Component named Shadow.qml that sets these:

anchors.fill: target
source: target

two properties. Here it is:

import QtQuick 2.0
import QtGraphicalEffects 1.0

DropShadow{
    id: root
    /*
    property string target
    anchors.fill: target
    source: target
    */

    //property alias target: root.anchors.fill | root.source

    /*
    property alias fill: root.anchors.fill
    property alias source: root.source
    */

    radius: 10
    samples: 15
    color: "black"
}

and in my usage, I can use it like this:

Shadow{
    anchors.fill: myTarget
    source: myTarget
}

and it works. The problem is I've to write myTarget in two places (i.e. anchors.fill and source) so I want to reduce it to a single line like this Shadow{ target: myTarget }

I've tried with each of those 3 commented out parts of Shadow.qml and none of those work!


Solution

  • The Target should not be a string it should be the Object on which the DropShadow should be applied to, which can be any kind of graphical Item

    property Item target
    anchors.fill: target
    source: target
    

    should work.
    However you can also just make it fill the source:

    anchors.fill: source
    

    now, instead of setting the target, you set the Source:

    Shadow {
        source: Rectangle { ... }
    }
    

    If the property name target is required, create an alias for source:

    DropShadow {
        property alias target: source
        anchors.fill: source
        ...
    }
    

    Creating an alias instead of a real property should be more efficient.