QML, a language designed for creating interfaces, was specifically made to be user-friendly for designers.
In a typical program setup, the logic is usually written in C++ while the user interface is built using QML. To bridge the gap between C++ and QML, it is essential to expose some C++ code to QML through various methods. One way is by making a C++ class accessible in QML, utilizing singletons, or injecting a QObject pointer into the QML environment. These techniques heavily rely on the Qt meta object system.
// Sample C++ code
class MyClass
{
Q_OBJECT
public slots:
int doSomething();
...
};
int main()
{
...
engine->rootContext()->setContextProperty("foo", new MyClass());
...
}
// Corresponding QML code
function foobar() {
var anInt = foo.doSomething();
}
While QML allows writing JavaScript and creating entire programs without touching C++, this approach is generally discouraged, especially if performance is crucial.
Contrary to popular belief, C++ is not used solely to enhance QML; rather, QML simplifies accessing C++ objects, enabling developers and designers to design sleek UIs without delving deep into C++.
When working with QML, my personal rule is to shift to C++ as soon as feasible. While simple functions can be created in QML, keeping them short and straightforward is vital to maximize the efficiency of the underlying QML and JS engines. Ensuring fast performance in QML can be challenging, as evidenced by the extensive page in Qt documentation outlining key considerations when using QML.