首页 > 解决方案 > 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?

标签: qtqmetaobject

解决方案


QMetaObject你那里得到QMetaProperty使用QMetaObject::property(QMetaObject::indexOfProperty(qPrintable(propName))),然后你可以打电话QMetaPropety::write(subscriber, value)(或writeOnGadget())。(显然您会存储索引而不是名称,该代码只是示例。)

和/或为了稍微提高效率,您可以使用它QByteArray来存储属性名称,因为这是与char *.


推荐阅读