Search code examples
c++qtqmlintegration

QtQuick, QML and C++ integration: how to make public variables definied inside .h file visible in QML file?


After integration C++ and QML using the way described here:

QML C++ integration

I have noticed only .h methods are visible outside class (from QML level), I have no access for public variables. After research I found that:

void QQmlContext::setContextProperty(const QString &name, const QVariant &value)

Is this way proper?

If not, how can I get access to my class public variables from QML level ?

Supposedly I can create functions for this purpose, but I don't like this way. It looks for me like way around...


Solution

  • In the following example, I wanted to expose the C++ qVersion() from QtGlobal to QML as System.qtVersion.

    //System.h
    #ifndef System_H
    #define System_H
    #include <QObject>
    class System : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(QString qtVersion READ qtVersion CONSTANT)
    public:
        System(QObject* parent = nullptr);
        QString qtVersion() const;
    };
    #endif
    
    //System.cpp
    #include "System.h"
    System::System(QObject * parent) :
        QObject(parent)
    {
    }
    QString System::qtVersion() const
    {
        return qVersion();
    }
    #endif
    
    ```c++
    //main.cpp
        //...
        qmlRegisterSingletonType<System>("qmlonline", 1, 0, "System", [](QQmlEngine*,QJSEngine*) -> QObject* { return new System(); } );
    

    I can access the above in QML with the following snippet:

    import QtQuick
    import QtQuick.Controls
    import qmlonline
    Page {
        Text {
            text: System.qtVersion
        }
    }
    

    You can try the QML portion online

    For other examples of C++ wrappings to QML checkout my GitHub projects: