简体   繁体   English

QML 定义了一个 object 属性

[英]QML defining an object property

I am trying to create a map in QML, the only way I've found to do this is:我正在尝试在 QML 中创建 map,我发现这样做的唯一方法是:

    readonly property variant translate: { "Hello" : "123" }

Then in the QML I can get 123 by using:然后在 QML 中,我可以使用以下方法获得 123:

    idOfItem.translate["Hello"]

This works fine and when doing this I get "123" returned as desired.这很好用,当我这样做时,我会根据需要返回“123”。 Now what I want to do is define another property to replace "Hello" which can be used in the QML, ideally something like:现在我想做的是定义另一个属性来替换可以在 QML 中使用的“Hello”,理想情况下是这样的:

    readonly property string strHello: "Hello"
    readonly property variant translate: { strHello : "123" }

Then in the QML:然后在 QML 中:

    idOfItem.translate[idOfItem.strHello]

This doesn't work and when trying to put strHello into the initial definition a read underscore appears under ":".这不起作用,当尝试将 strHello 放入初始定义时,读取下划线出现在“:”下。

Can this be resolved?这可以解决吗?

This is more of a JavaScript question/issue.这更像是一个 JavaScript 问题/问题。

You can create an object with dynamic property names, but not at declaration/initialization time.可以使用动态属性名称创建 object,但不能在声明/初始化时创建。 You have to do it dynamically, eg.:您必须动态执行此操作,例如:

readonly property string strHello: "Hello"
property var translate: ({})

function populate() {
  translate[strHello] = "123";

  console.log(translate[strHello]);
}

Component.onCompleted: populate();

See the following question, for example, but note that QtQuick doesn't support ES6.例如,请参阅以下问题,但请注意 QtQuick 不支持 ES6。 Is it possible to add dynamically named properties to JavaScript object? 是否可以将动态命名的属性添加到 JavaScript object?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM