Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently expose many C++ data members of a single object to QML?

Tags:

qt

qml

qtquick2

I have a C++ object pointer with many data members. I need them all available in QML. One obvious way would be to create a Q_PROPERTY for each member so they can be individually accessed via QML. However, if we are talking about dozens of data members, well that's a lot of lines of Q_PROPERTY, not to mention having to individually handle these in QML as separate properties as well (especially if dealing with "on changed" signals for each property).

I am wondering if it is possible to make a single Q_PROPERTY that would include all the data members I need. But what is not clear to me is the apparent mismatch between the types that QML supports and the types you can list in a Q_PROPERTY. For example, in QML, we have a basic string but its corresponding lising in a C++ Q_PROPERTY must be QString:

 Q_PROPERTY(QString datastring READ showdata NOTIFY datastringChanged)
  //in QML, `datastring` is just a plain string

Would there be more complex properties like lists or arrays that can be easily matched? QML has a list type and C++ has the QList but are these the same thing? Where can I find a listing of compatible types between C++ and QML?

On the other hand, having individual Q_PROPERTY for each data member could likely be better performance (my data is large and often changing) since the QML would not need to parse anything, perhaps.

like image 288
johnbakers Avatar asked Dec 10 '13 01:12

johnbakers


1 Answers

Would there be more complex properties like lists or arrays that can be easily matched? QML has a list type and C++ has the QList but are these the same thing? Where can I find a listing of compatible types between C++ and QML?

Have a look at the C++/JS data conversion help page. I think the list missed that QList<QObject*> is also possible.

On the other hand, having individual Q_PROPERTY for each data member could likely be better performance (my data is large and often changing) since the QML would not need to parse anything, perhaps.

Maybe, yes, depends on your performance needs. A C++ QList gets converted to a JavaScript list when accessed from QML/JS. That's a bit of conversion overhead indeed. Also, ff an item in the list changes, you need to emit the notify signal for the complete property, and every JS binding in which the list was used needs to be reevaluated, which will again be many list conversions. That could be better by having more fine-grained properties, but it really depends.

Btw, with Qt 5.1 there now is MEMBER, which makes writing Q_PROPERTYs a bit easier.

like image 80
Thomas McGuire Avatar answered Oct 15 '22 17:10

Thomas McGuire