How to set qml listview model in C++
-
Hi,
I dynamically create a custom qml listview in my C++ and it works great, but I can't set the model. Like others listview properties, I tried with "setProperty" but at runtime it can't find the model roles :
@
const MyListModel* myModel = new MyListModel();
myListView->setProperty("model", myModel);
@Someone has an idea ?
Regards
-
When you say you dynamically create a custom qml listview, do you have a ListView component in your qml file and creating an instance of it in your c++ code?? I don't see you using QDeclarativeCompoenent to load the component and create an object out of it?
Generally this is how it is done.
@
QDeclarativeView view;
QDeclarativeEngine *engine = view.engine();
QDeclarativeComponent component(engine, QUrl::fromLocalFile("listview.qml"));QObject *myObject = component.create();
myObject->setProperty("model",myModel);
@ -
Yes I do this, but my problem is that the model roles can't be found at runtime.
Which type of model do you use in your example ?
For my part, I use a derived class of QAbstractListModel. -
Ok.. I had a QList<QObject*> which I have set as model.
@
contactsList.append(new contactDetails(firstName, phoneNumber));ctxt->setContextProperty("favouritesModel", QVariant::fromValue(contactsList));
@where contactsList is
@QList<QObject*> contactsList;
@and contactDetails is a QObject derived class with two properties contactName and contactNumber.
I have not tried to set QAbstractListModel as a model.
-
You should have the roles set to your c++ model using setRoles. In QML simply specify the rolename in the model delegate
@
ListView {
id : myListView;
....
deletegate: myDelegate;Component {
id: myDelegate;
Text {
id: myText
text: myCustomTextRole // this is the name of the role you should handle in data() of model class
}
}
}
@ -
I solved my problem, I was trying to set directly a pointer to the "model" property of the qml listview but it can't be done like this. The solution is to use the QDeclarativeContext :
@
QDeclarativeEngine *engine = new QDeclarativeEngine();
QDeclarativeContext context = engine->rootContext();
MyListModel myModel = new MyListModel();
context->setContextProperty("myModelName", myModel);
myQMLListView->setProperty("model", context->contextProperty("myModelName"));
@