简体   繁体   中英

Qt Qml Javascript - Where to use which?

I'm new to Qt and Qml and I'm trying to figure out how they work together.
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 C++ is used. How C++ and JavaScript are connected? I'm pretty confused! and the docs doesn't help me either.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM