How to create a QML Item for a QML ListView in c++
-
Hi,
I tried to create a new QML Item for a ListView from c++, which works fine with setParentItem I can put it where ever I want.
But it doesn't work if I set a ListView as parent. I can see my new Item but it is not realy a part of the model so when create a second item it does not appear under the first.
I also tried to put the new item into the model which shows nothing. After all I found some examples how to manage the model thru a QList<Object*> but the I have no idea how to tell the delegate to draw it.Here is a small example:
MyItem.qml
@Rectangle {
width: 100
height: 70
color: "red"
}
@main.qml
@Rectangle {
width: 400
height:400
ListView {
id:thelist
anchors.fill: parent
clip: true
}
}
@inside a function on the c++ side I do:
@
QDeclarativeComponent component(ui->qmlView->engine(),QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();
QDeclarativeItem item = qobject_cast<QDeclarativeItem>(object);QObject* listobject = ui->qmlView->rootObject()->findChild<QObject*>("thelist"); QDeclarativeItem *listitem = qobject_cast<QDeclarativeItem*>(listobject); item->setParentItem(listitem);
@
Can someone give me a hint what I have to do to put the new item into the model for the listview
Thanks in advance,
lichti -
You definitely should set a delegate, then a model. Model should not be a visual item - the delegate is used to draw all items in a model.
You can use Column element instead of ListView if you want a bit more flexibility (at a price, of course, of loosing some features - but most can be mimicked with Flickable).
-
Hi sierdzio,
thank you for your answer. I got it working with a model and a delegate.
It takes a while that I understand fully how the delegate and model works together.
I think for simple Items this is the way to go, but for unknown complex items coming from another source imho its a big overhead.Cheers,
lichti -
Yes, ListView is intended for a list of items that look and behave roughly the same. It's optimised towards that use case.
This is why I proposed using Column as an alternative - it's more flexible, but also requires a bit more tinkering.