22

I want to do something similer to following code:

//test.qml
import QtQuick 1.0
Item 
{
    var globalforJs =10;

    function increment() // JavaScript function
    {
        globalforJs++;
    }
    ....
QML Code

Can we have global variable in QML file and access it from the JavaScript function?

TheOneTeam
  • 25,806
  • 45
  • 116
  • 158
psp1
  • 537
  • 2
  • 10
  • 19

3 Answers3

28

Try property int globalForJs: 10;

If you want a variable that can take any type:

property var globalForJs: 10

Prior to QML 2, use the variant keyword instead of var.

coyotte508
  • 9,175
  • 6
  • 44
  • 63
8

Using int or variant properties do not create a javascript variable, but rather a semantically different generic QML property (see here)

Before Qt 5, global javascript variables were recommended to be defined in a separately imported javascript file, however Qt 5 adds a var type property support.

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
-3

the thing which you want to make global should be done like in this example

property variant name:"john"//i want this to be global
onCreationCompleted(){
Qt.name = name
}

whereever you want to use the name property use like Qt.name instead of just name.this also applicable for any ids of controls

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90