How can you: application logic in C++ and presentation in QML

  • I just have some fun with QML and i love to use it to handle the UI, just UI!
    For me, I will define a new QML Elements in C++ with some method that handle the main (and maybe taking some time) application logic and use it at event handle for the presentation elements, like this:
    @Rectangle {
    width: 360
    height: 360
    CustomCppDefinedElements {
    MouseArea {
    anchors.fill: parent
    onClicked: {
    But is there any better way?

  • Moderators

    Who knows? Depends on what you need and what the circumstances are. What I usually do is either:

    create a base C++ class inheriting from QQuickItem, add relevant methods and properties, register it and use in code to create children components

    or create plain QObject classes in C++ and export methods with Q_INVOKABLE (or slots) and properties with Q_PROPERTY, and then register it with QQuickView's root object

    I won't venture to say which is better - it depends on a concrete use case.

  • In Qt5 with QtQuick2 there are more ways to expose C++ functionality to QML.
    One particularly useful feature is the ability to register a QObject singleton type with the QML typesystem. You can call functions, bind to properties, etc, without having to explicitly instantiate an element or pass in a context property.

    See the "documentation": for more information.

    In short, yes - QML was designed with C++ integration in mind. You should implement heavy application logic in C++, and implement only your UI with QtQuick, in many cases.


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.