22

I just want to know do we have any concept access specifiers like private property in QML as we have in C++.

If not if would like to know in case i have about 10 properties in my QML component but i have to limit the access to only 2 properties. how can we achieve this scenario.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
DNamto
  • 1,342
  • 1
  • 21
  • 42

1 Answers1

36

There is no such builtin feature in QML itself, but here is Qt Quick Components approach:

Item {
  property int sum: internal.a + internal.b
  QtObject {
    id: internal
    property int a: 1
    property int b: 2
  }
}

Properties of 'internal' object are invisible outside of Item, but may be freely used inside of it.

Pavel Osipov
  • 2,067
  • 1
  • 19
  • 27
  • is it a must to have `QtObject` or is it possible also to, for example, via this method to declare private property inside `ListView`? – KernelPanic Oct 05 '15 at 06:58
  • 2
    You can use any element you want instead of QtObject. – Pavel Osipov Oct 13 '15 at 08:15
  • 1
    From the docs: "It can be useful to create a QtObject if you need an extremely lightweight type to enclose a set of custom properties" - so using QtObject is the best thing to do for the purpose of the question here. – FourtyTwo Aug 30 '17 at 05:57
  • @FourtyTwo - yeah, extremely lightweight, only about 400-500 bytes when completely empty LOL. If there is another internal object, it would be better to use something you actually need than waste any extra memory on QtObject. On a side note, pretty silly to not have private specifier in QML, it wouldn't have been that hard to implement that feature. https://bugreports.qt.io/browse/QTBUG-60029?filter=-2 – dtech Sep 26 '17 at 23:04
  • 2
    Though I like your answer since it answers the original question, I think it might be better to instead use `_` or `__` prefixes as a convention to avoid the extra overhead of having `QtObject`s in every component. – pooya13 Sep 22 '20 at 19:25