Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Accessing properties by name and by number
pderocco last edited by
I have an object type that has close to 200 properties that need to be referred to by number, so that they can be queried and set by numeric messages containing a byte property number and a byte value. They are individual properties, rather than an array, because I need to bind to them individually. Right now, I'm doing something like this:
property int p0 // speed property int p1 // temperature property int p2 // azimuth // etc.
I bind to them by name with something like:
color: foo.p2 > 0 ? "red" : "green"
and access them by number with:
foo["p" + num] = val
This works reasonably well, but with such large numbers of them, and with the possibility that they could be renumbered in the course of this project, I'd rather be able to refer to them by name, yet I'm also concerned about efficiency.
One possibility would be to create named aliases:
property int p0; property alias speed: p0 property int p1; property alias temperature: p1 property int p2; property alias azimuth: p2 // etc.
But is there a run-time cost to property aliases? I would assume that both names must be listed in a dictionary at runtime, so would there be an extra lookup?
Another possibility is to define them with names, and then create an array that translates numbers into names:
property int speed property int temperature property int azimuth // etc. readonly property var properties: [ "speed", "temperature", "azimuth", // etc. ]
and then refer to them by number with
foo[properties[num]] = val
There's certainly a run-time cost to this, but how much? In QML's JS implementation, is a contiguous array of nothing but strings efficient? And how much slower is
I also thought about creating a C++ enumeration that translates names into numbers, but I don't believe that
foo["p" + Pnums.azimuth]would actually bind to
foo.p2, would it?
What I really wish QML had was a preprocessor that supported macros. I could then #define names as aliases for p0, p1, p2, etc., with zero run-time cost. But that apparently doesn't exist, so what's the best way to handle this, named aliases, an array of names, or something else I haven't thought of?
Best choice for you is define the Q_ENUM in C++ and expose the enumeration to QML. Use those enumeration. It should work as is.