Important: Please read the Qt Code of Conduct -

Defining constants for use in qml

  • Hi
    I am just getting started in qml.

    I have some c++ bindings in QML and i have some function like Myqmlhelper.getiovalue( 40,15) that i call from QML

    So i would like to now if qml supports declaring defines like in C, so i can write Myqmlhelper.getiovalue( PUMP,15) instead of Myqmlhelper.getiovalue( 40,15).

    in C i would have #define PUMP 40
    how can i do that in QML ?

    Or should i use enums in c++ instead of #defines and if so can i use them (enums) from QML ?


  • Moderators

    There is no equivalent to #define in QML, AFAIK. In my projects, I usually use root properties for this:
    // C++ code!
    QQuickView *myView = new QQV();
    QString pwd = qApp->applicationDirPath() + "/";
    myView->rootContext()->setContextProperty("PWD", pwd);

    Now PWD, holding current directory, is available from all QML files shown by that view. This is not a constant, of course, but if you use it as one, then it kind of becomes that ;)

  • With Qt5/QtQuick2 you can register a QML singleton type whose properties are the constants you require (Q_PROPERTY with CONSTANT flag, and also FINAL to ensure that the v4 engine can optimise). Such property resolutions should be as cheap as possible (and in the future, even greater optimisation is possible, such as hardcoding the constant at binding compilation time, so that the "binding" becomes a simple value initialisation).

    On a different tack - and I don't suggest you do this, because it's horrible - you can always use #define etc etc and manually pass your QML files through the C preprocessor as a build step. But don't do that, because it's evil, and you can't rely on it working in the future (eg, if the QML syntax is extended for some reason).


  • Q_ENUMS work great as replacement for constants in QML. You have to expose them from C++.

Log in to reply