Reputation: 13843
I'm looking for a simple way to share read-only values across multiple QML files, for instance; lets say I have a label element:
Label {
id: titleLabel
text: listView.currentItem ? listView.currentItem.text : "IDEAL Networks"
font.pixelSize: 20
elide: Label.ElideRight
horizontalAlignment: Qt.AlignLeft
verticalAlignment: Qt.AlignVCenter
Layout.fillWidth: true
color: red;
padding: {
left: 14
}
}
The color
and padding
values need to be used in other QML files and other areas of the same file.
Rather than re-typing red
and 14 in multiple locations is there a way I can create a shared library containing these values instead to make it easier to update globally at a later date?
* Update *
I've followed the instructions here: http://doc.qt.io/qt-5/qtqml-modules-qmldir.html
However when I import the custom CustomStyles 1.0
module I get an error - module "CustomStyles" is not installed.
//Style.qml with custom singleton type definition
pragma Singleton
import QtQuick 2.0
QtObject {
property int textSize: 20
property color textColor: "green"
}
// qmldir declaring the singleton type
module CustomStyles
singleton Style 1.0 Style.qml
// singleton type in use
import QtQuick 2.0
import CustomStyles 1.0
Text {
font.pixelSize: Style.textSize
color: Style.textColor
text: "Hello World"
}
Upvotes: 1
Views: 1425
Reputation: 244182
The solution is to use a singleton, in your case you must import it correctly, assuming that the .qml are in the same qrc you just have to do the following:
.qrc
<RCC>
<qresource prefix="/">
<file>main.qml</file>
[...]
<file>style/qmldir</file>
<file>style/style.qml</file>
</qresource>
</RCC>
Style.qml
pragma Singleton
import QtQuick 2.0
QtObject {
readonly property int padding: 20
readonly property color textColor: "green"
}
qmldir
singleton Style 1.0 Style.qml
main.qml
import QtQuick 2.0
import "style"
Text {
font.pixelSize: Style.textSize
color: Style.textColor
text: "Hello World"
}
In the following link there is an example
Upvotes: 5
Reputation: 49319
If your object tree is not too deep, it is applicable to simply declare the properties in the root object of main.qml
, which will make them resolvable from all qml files thanks to dynamic scoping, as long as you take care not to shadow them by identically named local properties.
If your tree is deep it will be more efficient to use a singleton, which will cut down the lookup time.
You can also chose a closer tree node, it doesn't have to be the root element, it just has to be deep enough so that all objects that need to access it are nested in it, and the properties have to be declared in the root element of the particular qml file in order to get dynamic scoping.
Upvotes: 1