nope
nope

Reputation: 47

declaring string in .qml files

I am trying to make a varaibles file in qml which declares several strings to be used by other qml files. for example: this would be Variables.qml

import QtQuick 2.0

Item {
    property var mystring: qsTr("hello world")
}

and I want to reference it in another file tab1.ui.qml

import QtQuick 2.4
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import "."

Item {
    Rectangle {
        id: rectangle
        color: "#3e1edd"
        anchors.fill: parent
        Text {
                id: text6
                anchors.fill: parent
                font.pixelSize: 12
                text: Variables.mystring
                visible: true
        }
    }
 }

this gives an error: Unable to assign [undefined] to QString

please tell me if there is a better way to manage variables. I want them to be global so they can be used in multiple frames. Thanks

Upvotes: 2

Views: 2413

Answers (1)

eyllanesc
eyllanesc

Reputation: 243975

You must use a singleton, for it you must create a folder that contains the .qml with "pragma Singleton" at the top and a qmldir that indicate the files:

Global
 ├── qmldir
 └── Variables.qml

qmldir

singleton Variables 1.0 Variables.qml

Variables.qml

pragma Singleton
import QtQuick 2.0

QtObject {
    property var mystring1: qsTr("hello world1")
    property var mystring2: qsTr("hello world2")
}

Then you must import and use it in the following way:

// others imports
import "Global"

// ...

    Text{
        // ...
        text: Variables.mystring1
    }

In this link you will find an example.

Upvotes: 4

Related Questions