Static Object Definition From QML



  • Hi everybody,
    I would like to know if it's possible to create a new "static" QML type from QML code. And then use its properties without having to instantiate that object.
    For instance:
    EnumerationCustomType.qml:

    import QtQuick 2.0
    
    QtObject {
        
        readonly property int one: 1
        readonly property int two: 2
        readonly property int three: 3
    }
    
    

    And then in main.qml:

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    
    ApplicationWindow {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        
        Label {
            anchors.centerIn: parent
            text: EnumerationCustomType.one
        }
    }
    

    This code does not work, this error is shown:

    ReferenceError: EnumerationCustomType is not defined
    

    P.S: I know that defining this object in main.qml it could be done:

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    
    ApplicationWindow {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        property var enumerationCustomType: EnumerationCustomType{}
        Label {
            anchors.centerIn: parent
            text: enumerationCustomType.one
        }
    }
    

    But I would like to do it without having to defining it.

    Thank you very much



  • Hi! You can use a singleton for that:

    EnumerationCustomType.qml

    import QtQuick 2.7
    
    pragma Singleton
    
    QtObject {
        readonly property int one: 1
        readonly property int two: 2
        readonly property int three: 3
    }
    

    qmldir

    singleton EnumerationCustomType 1.0 EnumerationCustomType.qml
    
    

    main.qml

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import "."
    
    ApplicationWindow {
        visible: true
        width: 640
        height: 480
    
        Column {
            Text { text: EnumerationCustomType.one }
            Text { text: EnumerationCustomType.two }
            Text { text: EnumerationCustomType.three }
        }
    
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.