0
votes

I want to create an object list model like in this example: http://doc.qt.io/qt-5/qtquick-models-objectlistmodel-example.html

To use it in QML I need to set the context property

ctxt->setContextProperty("myModel", QVariant::fromValue(dataList));

In the above example, this is done in the main.cpp, however, I would like to do this in the constructor of the class which defines the model. Is there a way to get the context in my class definition? If not, what is the best practice to set the context?

Edit: Some more context: I am doing a QQuickItem which should plot a line. This model I wanted to use to hold the properties of the ticks, namely pixel position and string label, therefore it does not need to be editable, and if the zoom changes all values will need to change. The ticks I then wanted to draw using a ListView with a custom delegate. Therefore, ideally I wanted to define my model inside the QQuickItem, which is then created in QML.

1
A list of QObejcts and a ListView for some ticks sounds like a gigantic waste of resources.dtech
And I thought I am following your suggestions :-) stackoverflow.com/questions/49150374/text-in-custom-qquickitem I am happy to describe it better in a chat, if you want.numberCruncher
The text label itself won't be an issue unless you are drawing hundreds. Bug it is puzzling as to why you need the QObjects part.dtech
Basically what I want: In my c++ QQuickItem I have a function which will give me a list of tick positions. These need to be drawn then. I just do not know what the best way is to get the c++ list into QML and then draw itnumberCruncher
Note that in that linked question you were taking about creating your own discrete text element, which couldn't possibly have been more efficient than simply using the QML Text. This is different from say if you draw the text as a part of the plot, without instantiating a bunch of text elements for each label.dtech

1 Answers

1
votes

Is there a way to get the context in my class definition?

Passing it as a constructor parameter should do the trick ;)

However, I would not recommend using such an object as a model. It is quick and dirty, emphasis on dirty. It is very inefficient when the model changes, because the view has to recreate everything, whereas a full fledged model will only reflect the actual changes.

Check this implementation out.

EDIT: After your clarifications, consider the following bit of documentation:

Certain C++ sequence types are supported transparently in QML as JavaScript Array types.

In particular, QML currently supports:

QList<int>
QList<qreal>
QList<bool>
QList<QString> and QStringList
QVector<QString>
std::vector<QString>
QList<QUrl>
QVector<QUrl>
std::vector<QUrl>
QVector<int>
QVector<qreal>
QVector<bool>
std::vector<int>
std::vector<qreal>
std::vector<bool>

All those are implicitly converted to JS arrays, and you can use JS arrays as model data directly.