How to access Q_property by its name ?



  • Example:

    class Test : public QObject
    {
    QOBJECT
    public:
    Q_PROPERTY(QString TestName READ GetTestName WRITE SetTestName)
    QString GetTestName();
    void SetTestName(QString name);
    };

    how to access the above property value ?
    can we use like below,

    QString str = TestName;

    I know that it can be done like QString str = GetTestName();

    But i need to do in the 1st method,, is that possible in QT ?? if not then wats the use of Q_Property ? directly we can manage through set & get functions..


    QObject.property("TestName").toString(); is not at all working.
    it is giving error for QObject.property("TestName") and string conversion is not at all possible.

    any other possible way ?


  • Moderators

    Please wrap all code on this forum between '@' tags.

    You can access the property using:
    @
    QObject.property("TestName").toString();
    @

    Where QObject is the instance of your Test class.



  • The use of properties is that you can access the properties of any QObject, even if you know nothing about it.

    Suppose you have a function that takes a QObject. You can check what properties are there, and you can use them:

    @void foo(QObject* obj)
    {
    // From help on QMetaObject::propertyCount()
    const QMetaObject* metaObject = obj->metaObject();
    QStringList properties;
    for(int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i)
    {
    properties << QString::fromLatin1(metaObject->property(i).name());
    }
    // Now you have a list of all properties names
    // But QMetaProperty also gives you a ton of other information, and you can use QMetaProperty::read and QMetaProperty::write to access the property
    }
    @

    "Gamma ray":http://www.kdab.com/kdab-products/gammaray/ is an excellent tool that allows you to view the properties of your objects while your application is running. It really shows the power of introspection.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.