Reputation: 500
I'm trying to figure out how Qt and Qml work together, because I'm confused about where to use C++ and where to use JavaScript.
Let's say I have a couple of QML objects (like forms, inputs, dropdowns, etc.). Now, obviously these components have some logic code. Should I write this logic code in JavaScript or in C++?
Let's say my input has a group of properties and signals. Where and how should these be coded?
If I should write it in JavaScript, then how is C++ used. How are C++ and JavaScript connected?
Upvotes: 4
Views: 3664
Reputation: 8311
The QML language was invented to be used to describe interfaces. It is meant to be simple to understand for designers.
This mean that in a program you will generally have all the logic implemented in C++ and the UI implemented in QML. To make the link between C++ and QML it is necessary to have some C++ code exposed to QML. There a many way to do that. For instance you could make a C++ class available in QML (see http://doc.qt.io/qt-5/qtqml-cppintegration-topic.html), just make the instance of a singleton available in QML or inject a QObject pointer into the QML environment. All of this heavily use the Qt meta object system (http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html).
// in C++
class MyClass
{
Q_OBJECT
public slots:
int doSomething();
...
};
int main()
{
...
engine->rootContext()->setContextProperty("foo", new MyClass());
...
}
// in QML
function foobar() {
var anInt = foo.doSomething();
}
QML allowing you to write javascript you can also write a complete program without ever using C++, implementing everything in javascript. But this is generally a bad idea, especially if you need performances.
Unlike some say, C++ is not here for extending QML. But QML is here to offer a simple interface to C++ objects, allowing developers and designers to create fancy UI without typing/learning C++.
My personal rule when writing QML is to go to C++ as soon as possible. Sure you can write simple functions in QML, but you have to keep them short and simple to leverage the full power of the optimizations of the underlying QML and JS engines. Keeping QML fast is so hard there is a full page in Qt documentation of what to think about when using QML (http://doc.qt.io/qt-5/qtquick-performance.html).
Upvotes: 4