4

How do I bind to a Javascript resource?

I'm new to QML and are probably thinking about this the wrong way, but in the below example, I'd like the button to say "World" when I press it.

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.0
import "model.js" as Model


Button {
    id: button
    text: Model.text

    onClicked: {
        Model.text = "World";
        print("Model.text is:", Model.text)
        print("button.text is:", button.text)
        // Model.text is "World"
        // button.text is "Hello"
        // They should both be "World"
    }
}

model.js

var text = "Hello";

I also tried using a Qt.binding, but it didn't make a difference.

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.0
import "model.js" as Model


Button {    
    onClicked: {
        Model.text = "World";
    }

    Component.onCompleted: {
        text = Qt.binding(function () { return Model.text })
    }
}

The end result I'm looking for is to have properties in a dedicated Javascript resource, such as window height, colors and image paths etc. and have whichever item is using them to stay in sync with any changes made to the resource.

Edit

Found a related question: declare global property in QML for other QML files

Community
  • 1
  • 1
Marcus Ottosson
  • 3,241
  • 4
  • 28
  • 34

1 Answers1

5

Generally, you can't bind QML property to variable from pure JavaScript module. My advice is to use lightweight QML alternative - QtObject . You can add custom set of properties and signals to it, for example:

QtObject {
    id: mySettings
    property string iconPath: "./icon.png"
}

This properties can be binded later exactly as you want.

QtRoS
  • 1,149
  • 1
  • 16
  • 23
  • I was contemplating this, and it might work well in my case. If I really wanted to keep it within the Javascript realm, perhaps I could even `mySettings = Qt.createQmlObject("import QtQuick 2.0; QtObject {}")` and attach properties from there? – Marcus Ottosson Nov 25 '14 at 09:06
  • 1
    After some experiments and thought, this one is a winner. Thanks a bunch @QtRoS. – Marcus Ottosson Dec 06 '14 at 12:31