Can I construct a custom Qml item that contains a placeholder child?



  • I have a series of items that I need to apply the same OpacityMask to, and to simplify my code I'd like to create something like this:

    MaskedItem.qml:
    @Item {
    MyMaskSource {
    id: maskSource
    anchors.fill: parent
    visible: false
    }

    (Placeholder) {
        id: item
        anchors.fill: parent
        visible: false
    }
    
    OpacityMask {
        anchors.fill: parent
        source: item
        maskSource: maskSource
    }
    

    }
    @

    That way, in my main Qml, I can do something like this:

    @RowLayout
    {
    MaskedItem {
    Image {
    source: "Image1.png"
    }
    }
    MaskedItem {
    Image {
    source: "Image2.png"
    }
    }
    }
    @

    But I can't figure out how to do that "placeholder" in my MaskedItem. I thought about doing some JavaScript but that's also eluding me:

    MaskedItem.qml:
    @Item {
    default property Item myItem

    onItemChanged: {
    children.add(myItem);
    myItem.visible = false;
    myItem.anchors.fill = this;
    OpacityMask* mask = new OpacityMask;
    mask.anchors.fill = this;
    mask.source = myItem;
    mask.maskSource = maskSource;
    children.add(mask);
    }

    MyMaskSource {
        id: maskSource
        anchors.fill: parent
        visible: false
    }
    

    }
    @

    Any suggestions? I'm pretty new to Qml so I may be missing something obvious!

    Thanks,
    Chris



  • Have you tried making your item the default property (http://qt-project.org/doc/qt-5/qtqml-syntax-objectattributes.html#default-properties) of MaskedItem?

    Alternatively you could try working with a Loader element.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.