jabuj
jabuj

Reputation: 3659

How to create a singleton QML type in Qt6 using cmake?

I want to create a singleton QML type, preferably without any C++ code. Here is what I tried:

// ./themes/Theme.qml
pragma Singleton
import QtQuick

QtObject {
    readonly property string color: "indigo"
}
// ./Main.qml
import QtQuick
import QtQuick.Window
import "./themes"

Window {
    color: Theme.color
    // ...
}

However it doesn't work: all properties on Theme in Main.qml are undefined. The suggestions I have seen are to add this line to qmldir:

singleton Theme 1.0 themes/Theme.qml

However qmldir is not supposed to be written manually in qt6, as it is generated automatically on build, and doing this doesn't work anyway. Another way is using qmlRegisterSingletonType from C++, but I don't really want to use C++ for this, and if I do this my singleton must be imported specifically as import Theme 1.0 and not as other local .qml files (which can simply be used without any import statements if the file is in the same directory, or using import "./path/to/dir" otherwise).

Is there a way to do this only in QML?

Upvotes: 5

Views: 1965

Answers (2)

Stephen Quan
Stephen Quan

Reputation: 26324

Usually, you put the qmldir inside the Themes folder, and the source would be updated to omit the Theme folder, i.e. singleton Theme 1.0 Theme.qml.

import QtQuick
import QtQuick.Controls
import "themes"
Page {
    background: Rectangle { color: Theme.color }
}

// themes/Theme.qml
pragma Singleton
import QtQuick

QtObject {
    readonly property string color: "indigo"
}

// themes/qmldir
singleton Theme 1.0 Theme.qml

You can Try it Online!

Upvotes: 1

jabuj
jabuj

Reputation: 3659

Yes, it is possible. Only marking your .qml file with pragma Singleton is indeed not enough, it also must be marked as singleton in qmldir. But since qmldir is generated automatically, you need to specify that a particular file contains a singleton in cmake configuration. Add this to your CMakeLists.txt file and make sure it is written before the call to qt_add_qml_module:

set_source_files_properties(themes/Theme.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)

Upvotes: 4

Related Questions