简体   繁体   中英

Qml / Qt creator: How to “spawn”/create a custom component multiple times

Trying to make a UI for a program in Qt creator.

I got a scroll view where I want to place a custom component (a rectangle). I can manually put the component in there multiple times and scroll up and down so got that working.

My problem is that I want to generate the component automatically when the user presses a button.

So my question is how to "generate/spawn/create" a custom component into a scroll view when the user presses a button

So far I've tried with loaders and calling the custom component directly inside an onClicked function but this does not seem to work.

var component = Qt.createComponent("CustomComponent.qml");

 onClicked: { component.createObject(column);

I am trying to create the component inside a column with the id column

you can compare what I am trying to achieve with a social media feed. Where I got a list that is scrollable and I want to put components(atm just a rectangle) in the list.

You can use Repeater for that:

Repeater {
    id: repeater
    model: 0

    CustomComponent {}
}

Button {
    onClicked: {
        repeater.model += 1;
    }
}

Repeaters can be used in positioning items(Row, Column, Grid) and layouts. Also it is possible use a list as a model. So in that case you can reach model data(model[index]) with modelData and index with index in your custom component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM