Global functions or macros to get Qt version in QML code

Viewed 1427

How Can I get Qt version, for example 5.11.2 or similar, in my QML code. In my C++ code I have these options:

Method available on C++:

qVersion();

Macro available on C++:

QT_VERSION

But I couldn't find anything on QML?

1 Answers

You could use a Context Property, as explained here.

A simple example, given a simple qml file like this:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {

    Text {
        text: qtversion
    }

    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
}

Set the qtversion property at startup, in main function:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("qtversion", QString(qVersion()));
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;    

    return app.exec();
}
Related