Different ways of exposing data to qml
-
I feel like this documentation is very good : http://doc.qt.io/qt-5/qtqml-cppintegration-overview.html , just forget about the Interacting with QML Objects from C++ section, it's generally considered bad practice (https://youtu.be/vzs5VPTf4QQ?t=23m19s & the relevant warning in the linked section).
If you have questions left answered after reading this, you can ask them then here. It's better than starting to paraphrasing the good Qt documentation.
-
Another resource: https://qmlbook.github.io/en/ch15/index.html
-
@Nitheesh said in Different ways of exposing data to qml:
Could you please explain the differences between Qqmlcontext and qmlregistertype with examples?
No examples here, just explanation.
You register a type if you want to have a new type in QML. Think about those which you use in QML: Item, Text, Rectangle... Now you want to have a new type but creating it in a normal QML way, extending an existing one in QML syntax, isn't enough for you. Think about
Item{property string name:""}
It is a component which has the same name than the file it is in. But you want special behaviour which you can't easily do in QML and you want a reusable type from which you can create QML objects. You can implement it in C++ and register it. You don't create or destroy those objects in C++ but in QML, just like other QML objects.
So, it's a way to extend the QML type system.
I suppose by QQmlContext you mean QQmlContext::setContextProperty(). You can write a C++ class which inherits QObject and then create an object of that class in C++. Then you can set is as a context property for QML. It becomes a global object in your QML. Its public slots, signals, Q_INVOKABLE functions and some other are visible and usable in QML/javascript as if it were a QML object with properties and functions. But the object is just one global object, you don't create or destroy it in QML but in C++.
So, it's a way to expose your C++ objects, created and living in C++, to be used in your QML code.
-
@Nitheesh Another way to think about it could be this:
There are simplistically said basically two differents way to write an application with QML.
One is to minimize the C++ part: you can have only main.cpp with no C++ objects (other than the QML engine) in it, and you write your app with QML and javascript. Now you can extend the QML type system by writing a class in C++, but you don't use it in C++. You just register the class.
The second is to have a C++ backend/business logic with several classes, and objects of those classes when the app is run. Think about a GUI agnostic library, engine or server program. Now you can expose as context properties some C++ objects of that backend to the QML GUI so that runtime interaction between the GUI and the backend is possible.
Actually only the latter, context property, is a way of "exposing data to qml", if by that you mean exposing runtime C++ objects from a C++ backend.