Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

properties - How do you assign a QML Item to a component property in QML and then use that object inside the component?

I'm trying to create a QML object that acts like a wrapper for other objects. Here's my QML file (Container.qml):

Item {
    property string label
    property Item control

    Row {
        Label {
            text: label
        }

        // Not sure how to display the control assigned to the control property
    }
}

What I would like to do (in my QML that consumes this component) is something like this:

Container {
    label: "My Label"
    control: Textbox {
        text: "My Value"
    }
}

When fed that QML the result (in the interface) should be something resembling the output from this QML:

Item {
    Row {
        Label {
            text: "My Label"
        }
        Textbox {
            text: "My Value"
        }
    }
}

Is this possible? When I try to do this I get "cannot assign object to property" when assigning an Item to the control property. I've searched the Qt forums and Googled this mercilessly, but no success. If anybody knows the answer it would be greatly appreciated.

Thanks

Jack

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is much better solution:

/* MyObject.qml */

Rectangle {
    default property alias data /* name can be any */ : inner_space.data

    /* ... You can put other elements here ... */
    Item {
       id: inner_space

       /* ... Params ... */
    }
    /* ... You can put other elements here ... */
}

And now we can do all we want!

/* main.qml */

Rectangle {
    MyObject {
        Button {
             /* ... */
        }
    }
}

Thanks to user bobbaluba for suggesting to use the data property rather than children.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...