qtqmetaobject

Set property value of QObject by index, not name


In my publisher-subscriber class the Qt components subscribe by their property names. The publisher maps the pairs <QObject*,PropertyName (as QString)> to the names of the publishable variables.

{ VarName -> [(QObject*, PropName)] }

On variable change, the list of subscribed QObjects are called using setProperty:

subscriber->setProperty( PropName.toAscii().constData(), NewValue );

I'd like to optimize the conversion from QString to char*. Also I assume, internally in setProperty the property setter function is found by going through the list of const* and string compare.

QMetaObject provides the method:

int QMetaObject::indexOfProperty(const char *name) const

which I could use during the subscription to get the index and later on the value change use only Index instead of the string-name.

But how can I invoke the property setter by the index? Is it possible at all?


Solution

  • From QMetaObject you would get the QMetaProperty using QMetaObject::property(QMetaObject::indexOfProperty(qPrintable(propName))) and then you can call QMetaPropety::write(subscriber, value) (or writeOnGadget()). (Obviously you'd store the index instead of the name, that code is just for example.)

    And/or for a slight efficiency gain you could use QByteArray to store the property names since that's one less conversion step to/from char *.