How to Access ListModel from C++
-
I have found many posts related to getting custom models into QML, but in my case I am very happy with the ListModel and simply want to make it available to C++. However, I am running into a crash which gives no feedback and I'm at a bit of a loss for how to continue.
Here is the relevant code snippet from how I try accessing the model from C++
C++:
Q_PROPERTY(QAbstractListModel* model READ model WRITE setModel) QAbstractListModel* model() const {return model_;}; void setModel(QAbstractListModel *model){}; QAbstractListModel* model_;
QML:
ListModel { id: textModel } TextBalloon { model: textModel }
Output:
QML debugging is enabled. Only use this in a safe environment. 05:38:08: The program has unexpectedly finished.
Very frustrating not to have a more useful error message. It just bombs out. The debugger is no help, it gets stuck on
view.setSource(QUrl("qrc:/qml/main.qml"));
.The program loads correctly when I remove the
model: textModel
line.Anyone have a working example of accessing the ListModel from C++?
-
Best thing is to avoid accessing qml objects from c++. If you do some mistake it will crash like this. You have go deep inside object tree to find your list model and then access it
-
See if this helps.
-
Can you post a simple example where your code crashes so that we can reproduce it ?
What is the body of yoursetModel
method ?Accessing QML objects like that is perfectly fine and not a bad practice since you are passing it to c++, it's not the c++ retrieving it with a
findChild
call.The video linked is about using a c++ model in a QML view, that's not relevant to OP's problem.
-
I'm attributing this to the build system. The problem resolved itself when I started from a blank generic example and copied over the code before putting it back into the problematic app.
The only thing I can think of is that perhaps I needed to do a
make clean
.