2

I am trying to create a map in QML, the only way I've found to do this is:

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

Then in the QML I can get 123 by using:

    idOfItem.translate["Hello"]

This works fine and when doing this I get "123" returned as desired. Now what I want to do is define another property to replace "Hello" which can be used in the QML, ideally something like:

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

Then in the QML:

    idOfItem.translate[idOfItem.strHello]

This doesn't work and when trying to put strHello into the initial definition a read underscore appears under ":".

Can this be resolved?

SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • you've define an object that has property named `strHello` and its value is `123`. The object has no property named `Hello`. you should use `[]`, not `{}` if you want to define array, not object. But I strongly advise you to get some JavaScript tutorial first to learn it. – folibis Nov 21 '19 at 09:23
  • @folibis, I'm very fluent in JavaScript, the property strHello contains the key "Hello" which does exist in the object and its this I want to use to lookup... – SPlatten Nov 21 '19 at 09:35

1 Answers1

2

This is more of a JavaScript question/issue.

You can create an object with dynamic property names, but not at declaration/initialization time. 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. Is it possible to add dynamically named properties to JavaScript object?

Maxim Paperno
  • 4,485
  • 2
  • 18
  • 22
  • 1
    I understand how it can be done in JavaScript, I couldn't find an equivalent constructor in QML, there is onCompleted as you have posted, is this the correct place to initialise properties? – SPlatten Nov 21 '19 at 09:33
  • Well depends on your code/style/etc, but yes, that's a pretty typical place to init things within Components. Really depends on where/how your `translate` object exists in relation to what uses it, etc. BTW if this is literally for translation purposes then hopefully you already know about [qsTr()](https://doc.qt.io/qt-5/qtquick-internationalization.html) and such (which can be used for other text abstraction besides internationalization). – Maxim Paperno Nov 21 '19 at 09:39
  • Thank you, I will investigate. – SPlatten Nov 21 '19 at 09:41