Javascript 我们可以在 QML 文件中声明全局变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7515598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:34:30  来源:igfitidea点击:

Can we declare global variable in QML file?

javascriptqml

提问by psp1

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 fileand access it from the JavaScript function?

我们可以使用全局变量QML file并从 JavaScript 函数访问它吗?

回答by coyotte508

Try property int globalForJs: 10;

尝试 property int globalForJs: 10;

If you want a variable that can take any type:

如果您想要一个可以采用任何类型的变量:

property var globalForJs: 10

property var globalForJs: 10

Prior to QML 2, use the variantkeyword instead of var.

在 QML 2 之前,使用variant关键字而不是var.

回答by ?arūnas Vala?kevi?ius

Using intor variantproperties do not create a javascript variable, but rather a semantically different generic QML property (see here)

使用intvariant属性不会创建 javascript 变量,而是创建语义不同的通用 QML 属性(请参阅此处

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

在 Qt 5 之前,建议在单独导入的 javascript 文件中定义全局 javascript 变量,但是 Qt 5 添加了var类型属性支持

回答by John Ankanna

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.nameinstead of just name.thisalso applicable for any ids of controls

无论您想在何处使用 name 属性,请使用 likeQt.name而不是name.this也适用于任何控件的 id