Important: Please read the Qt Code of Conduct -

Constants in qml files

  • We are using QT creator because a vendor used it and therefore now we are. There are multiple places where the same constants are used over and over again. Having written C and C++ for a long time I want to get rid of those magic numbers and put in constants. So I added a file named constants.qml and populated it with things like:
    const int MAX_SCREEN_WIDTH = 480;
    because all the QML stuff looks quite a bit like C code. When I included that in another qml file with:
    include constants.qml
    I was not real surprised it did not work. From the QT documents web page searches for "constant" and for "keyword const" were not productive.
    What is the syntax to use for creating a QML file with a list of constants for all the other QML files to use? That way I can replace all the lines of:
    width: 480

  • Lifetime Qt Champion

    as far as i know there is not const in QML
    Javascript has it so maybe you can use that.

  • Moderators

    @BKBK you can make your properties readonly

    readonly property <propertyType> <propertyName> : <initialValue>
    Read-only properties must be assigned a value on initialization. After a read-only property is initialized, it no longer possible to give it a value, whether from imperative code or otherwise.

    on the other hand, I believe one is supposed to do this in a cpp class.
    Here an quick and dirty example:


    class GlobalConsts : public QObject{
        Q_INVOKABLE inline const int &a(){return m_a;}
        Q_INVOKABLE inline const int &b(){return m_b;}
    const int m_a = 21;
    const int m_b = 42;


    qmlRegisterType<GlobalConsts > ("MyConsts",1,0,"GlobalConsts");

    //qml usage

    import MyConsts 1.0
    MyConsts {
        id: constants
         x:    constants.a()
         y:    constants.b()

  • @J.Hilk It's saying MyConsts is not a type :(

Log in to reply