Home > Mobile >  QObject set/get property with index operator
QObject set/get property with index operator

Time:12-06

Why didn't Qt set/get properties through the index operator [] ? Is there any good reason for this that I don't know about? Thanks.

CodePudding user response:

I don't see any clear benefit to using the indexing operator, but here is a major downside:

Qt objects are usually referenced using pointer (ie. QWidget*). If Qt used operators for accessing properties, it would be very easy to end up using the indexing operator on the pointer Consider the following:

void doSomethingWithProperty(QWidget* widget) {
   auto& propertyValue = widget[0];
}

propertyValue here would not be the result of the indexing operator on QWidget/QObject if there was one because we can treat pointers like arrays in C/C (note that this is sometimes considered a bad practice). It would be a reference to the widget. To instead call the operator on the type, you would need something like (*widget)[0] which is not nice to write.

Maybe you use strings for the operator parameter... but then it isn't clear to me what the operator does. Qt objects have child objects. Does (*widget)["thing"] return a property named thing or does if find a child object named thing? It is not obvious to me which one it should be.

  • Related