I have a custom qml element based on a textbox. I want that whenever the user presses on the last textbox in the VisualItemModel, a new textbox is added automatically. There is a way to do this with ListModel (using append()), but nothing with VisualItemModel.
How to do this? Even Javascript will help.
1 Answer
Seems like VisualItemModel
wasn't really intended for dynamic management - it is a purely static construct.
VisualItemModel
is a lazy and clumsy solution to get a list view to show different elements, cramming together the data and UI. If that is point, you can easily achieve this by using a standard ListModel
and for the ListView
:
ListView {
anchors.fill: parent
model: mod
delegate: Loader {
source: name + ".qml"
}
}
Then you can append to the model like this:
mod.append({"name" : "ItemName"})
Then in the list view, the delegate will create the appropriate element for each list entry.
If you don't want to have separate sources for the items, you can wrap different items in a Component
and in the Loader
instead of source
set the sourceComponent: name
:
Component {
id: c2
Rectangle {
width: 200
height: 100
color: "blue"
}
}
....
mod.append({"name" : c2})
But in your case you don't seem to need different elements to have different UIs, therefore you don't really need VisualItemModel
as well. Just make the view delegate a text box and append to a standard ListModel
and you will get another text box.
-
Yep. That's what I realised finally that since delegate is a way how the UI looks, we don't need a VisualListItem at all. I had figured it out, but thanks for answering anyway.– aceBoxMar 14, 2015 at 22:11
-
Well, u can just use a numerical model, i.e.
model: 0
, so that, u can just writemodel += 1
to add a new delegate. Mar 15, 2015 at 2:13 -
@BaCaRoZzo - that's the fastest way probably, but it is very inefficient because the entire view is redrawn as the number changes, whereas with a model only the changes are updated.– dtechMar 15, 2015 at 11:06
-
@ddriver Well, that's something that depends on your requirements. Surely it's more inefficient than the list but yeah, it's another way. :) The list provides build-in transition handling properties for addition/removal, which is also another point for that approach. Mar 15, 2015 at 13:29
-
2@BaCaRoZzo - it is not just that - since the entire listview is redrawn, that means any text the OP might have entered in his text boxes will be lost each time he adds another - now that would be very backward. With a model it won't happen, plus the model can provide data storage for the text in those boxes.– dtechMar 15, 2015 at 13:46