C

Defining singletons in QML

Qt Quick Ultralite allows you to define a singleton in QML. Follow these steps to define a singleton:

  • Add pragma Singleton at the beginning of the file
  • Add the Singleton QML file to a QmlProject-defined QML module

The Singleton pragma is allowed only for QML files within a QML module.

Example

The Singleton QML file:

pragma Singleton
import QtQuick 2.15

QtObject {
    property string text: "MyQmlSingleton"
}

The module .qmlproject file:

import QmlProject 1.3

Project {
    MCU.Module {
        uri: "MyQmlSingleton"
    }

    QmlFiles {
        files: [
            "MyQmlSingleton.qml"
        ]
    }
}

The main .qmlproject file:

    ModuleFiles {
        files: [
            "MyQmlSingleton.qmlproject"
        ]
    }

The main QML file:

import QtQuick 2.15
import MyQmlSingleton

Rectangle {
    Text {
        text: MyQmlSingleton.text
    }
}

See also MCU.Module.

Available under certain Qt licenses.
Find out more.