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?
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.
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 .
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With