Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global functions or macros to get Qt version in QML code

Tags:

c++

qt

qml

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?

like image 977
user3405291 Avatar asked Nov 12 '18 07:11

user3405291


People also ask

What is difference between Qt and QML?

QML is the language; its JavaScript runtime is the custom V4 engine, since Qt 5.2; and Qt Quick is the 2D scene graph and the UI framework based on it. These are all part of the Qt Declarative module, while the technology is no longer called Qt Declarative.

How do you call a C++ function from QML?

For any C++ code to be called from QML, it must reside inside a QObject . What you need to do is create a QObject descended class with your function, register it to QML, instantiate it in your QML and call the function. Note also that you have to mark your function with Q_INVOKABLE .

What is Q_property in QML?

A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived class are accessible from 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();
}
like image 83
p-a-o-l-o Avatar answered Sep 18 '22 16:09

p-a-o-l-o