Model from C++ to QML
-
Hello,
I thought this must be mentioned hundred times everywhere but after spending many hours searching the Internet, I didn't find anything really useful.
What I want to do is very simple. I have some data which I read from database (in C++ code) and I want to display them in my QML UI. I know that I need to subclass QAbstractListModel and then bind it to my QML.
I already implemented this in Python (PySide) and Qt4 but now I'm converting my program to C++ and Qt5. I'm afraid I won't be able to do it correctly without an example or a guide. But unfortunately I couldn't find any. I found some Qt 4.x examples but also I saw some information that it was changed in Qt5.
Do you know about any guide or working example on using QAbstractListModel and ListView? Thank you.
-
-
shkryab> Thanks a lot, this is exactly what I was looking for. I don't know why I couldn't find it...
-
I managed to create the model without any problems. But unfortunately I ran into another issue.
I need to create variable number of ListViews and be able to index them by number. In Python/PySide I created a list of models and binded it to my QML. This seems to be a problem in C++.
@QList<MyModel*> myModels;
ctxt->setContextProperty("models", myModels);
@This seems to be not working. Do you have any idea how I should implement it? Maybe a 2-dimnesional model? Or something different?
-
You should register your type or use QObject*.
@
QList<QObject*> myModels;
ctxt->setContextProperty("models", myModels);
@And use "QQmlListProperty":http://qt-project.org/doc/qt-5.1/qtqml/qqmllistproperty.html instead QList.
-
Thanks a lot, I finally managed to do what I needed. If someone else would read this topic, I found some useful information also "here":http://stackoverflow.com/questions/17083398/calling-setcontextproperty-with-a-qlistmyobject
Now I'm facing one more problem (I hope the last one). :-) Following the guide I have this function in "myModel":
@void LibraryModel::addItem(const LibraryItem &item)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_items << item;
endInsertRows();
}
@If I add some items to my list model, it is not shown immediately. Sometimes it appears after a few seconds, sometimes never. What am I missing? Do I have to emit a signal that the model has changed? I thought the functions beginInsertRows() and endInsertRows() is meant to do this.
Another question is, if I should call addItem for each item (I'm reading database results and appending it one by one) or should I rather store all the list items in a list and then implement in my model addItems function, to add all the items at once? I hope it is understandable what I'm asking...
-
So, the problem was that I was filling the model from a background thread, which doesn't work. I implemented a signal and a slot in main GUI thread, which fills the model and now it works fine.
I got the help in "this thread":http://qt-project.org/forums/viewthread/28884/.