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 CMakeLists.txt file:

qul_add_qml_module(myqmlsingleton-module
    URI MyQmlSingleton
    QML_FILES
        MyQmlSingleton.qml
)

target_link_libraries(my-app PRIVATE myqmlsingleton-module)

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.