Home · All Namespaces · All Classes · Main Classes · Grouped Classes · Modules · Functions

Qt's Property System

Qt provides a sophisticated property system similar to the ones supplied by some compiler vendors. However, as a compiler- and platform-independent library, Qt does not rely on non-standard compiler features like __property or [property]. The Qt solution works with any standard C++ compiler on every platform Qt supports. It is based on the Meta-Object System that also provides inter-object communication via signals and slots.

Requirements for Declaring Properties

To declare a property, use the Q_PROPERTY() macro in a class that inherits QObject.

 Q_PROPERTY(type name
            READ getFunction
            [WRITE setFunction]
            [RESET resetFunction]
            [DESIGNABLE bool]
            [SCRIPTABLE bool]
            [STORED bool]
            [USER bool])

Here are some typical examples of property declarations taken from class QWidget.

 Q_PROPERTY(bool focus READ hasFocus)
 Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
 Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor RESET unsetCursor)

A property behaves like a class data member, but it has additional features accessible through the Meta-Object System.

The READ, WRITE, and RESET functions can be inherited. They can also be virtual. When they are inherited in classes where multiple inheritance is used, they must come from the first inherited class.

The property type can be any type supported by QVariant, or it can be a user-defined type. In this example, class QDate is considered to be a user-defined type.

 Q_PROPERTY(QDate date READ getDate WRITE setDate)

Because QDate is user-defined, you must include the <QDate> header file with the property declaration.

For QMap, QList, and QValueList properties, the property value is a QVariant whose value is the entire list or map. Note that the Q_PROPERTY string cannot contain commas, because commas separate macro arguments. Therefore, you must use QMap as the property type instead of QMap<QString,QVariant>. For consistency, also use QList and QValueList instead of QList<QVariant> and QValueList<QVariant>.

Reading and Writing Properties with the Meta-Object System

A property can be read and written using the generic functions QObject::property() and QObject::setProperty(), without knowing anything about the owning class except the property's name. In the code snippet below, the call to QAbstractButton::setDown() and the call to QObject::setProperty() both set property "down".

 QPushButton *button = new QPushButton;
 QObject *object = button;

 button->setDown(true);
 object->setProperty("down", true);

Accessing a property through its WRITE accessor is the better of the two, because it is faster and gives better diagnostics at compile time, but setting the property this way requires that you know about the class at compile time. Accessing properties by name lets you access classes you don't know about at compile time. You can discover a class's properties at run time by querying its QObject, QMetaObject, and QMetaProperties.

 QObject *object = ...
 const QMetaObject *metaobject = object->metaObject();
 int count = metaobject->propertyCount();
 for (int i=0; i<count; ++i) {
     QMetaProperty metaproperty = metaobject->property(i);
     const char *name = metaproperty.name();
     QVariant value = object->property(name);
     ...
 }

In the above snippet, QMetaObject::property() is used to get metadata about each property defined in some unknown class. The property name is fetched from the metadata and passed to QObject::property() to get the value of the property in the current object.

A Simple Example

Suppose we have a class MyClass, which is derived from QObject and which uses the Q_OBJECT macro in its private section. We want to declare a property in MyClass to keep track of a priorty value. The name of the property will be priority, and its type will be an enumeration type named Priority, which is defined in MyClass.

We declare the property with the Q_PROPERTY() macro in the private section of the class. The required READ function is named priority, and we include a WRITE function named setPriority. The enumeration type must be registered with the Meta-Object System using the Q_ENUMS() macro. Registering an enumeration type makes the enumerator names available for use in calls to QObject::setProperty(). We must also provide our own declarations for the READ and WRITE functions. The declaration of MyClass then might look like this:

 class MyClass : public QObject
 {
     Q_OBJECT
     Q_PROPERTY(Priority priority READ priority WRITE setPriority)
     Q_ENUMS(Priority)

 public:
     MyClass(QObject *parent = 0);
     ~MyClass();

     enum Priority { High, Low, VeryHigh, VeryLow };

     void setPriority(Priority priority);
     Priority priority() const;
 };

The READ function is const and returns the property type. The WRITE function returns void and has exactly one parameter of the property type. The meta-object compiler enforces these requirements.

Given a pointer to an instance of MyClass or a pointer to an instance of QObject that happens to be an instance of MyClass, we have two ways to set its priority property.

 MyClass *myinstance = new MyClass;
 QObject *object = myinstance;

 myinstance->setPriority(MyClass::VeryHigh);
 object->setProperty("priority", "VeryHigh");

In the example, the enumeration type used for the property type was locally declared in MyClass. Had it been declared in another class, its fully qualified name (i.e., OtherClass::Priority) would be required. In addition, that other class must also inherit QObject and register the enum type using Q_ENUMS().

A similar macro, Q_FLAGS(), is also available. Like Q_ENUMS(), it registers an enumeration type, but it marks the type as being a set of flags, i.e. values that can be OR'd together. An I/O class might have enumeration values Read and Write and then QObject::setProperty() could accept Read | Write. Q_FLAGS() should be used to register this enumeration type.

Dynamic Properties

QObject::setProperty() can also be used to add new properties to an instance of a class at runtime. When it is called with a name and a value, if a property with the given name exists in the QObject, and if the given value is compatible with the property's type, the value is stored in the property, and true is returned. If the value is not compatible with the property's type, the property is not changed, and false is returned. But if the property with the given name doesn't exist in the QObject (i.e., if it wasn't declared with Q_PROPERTY(), a new property with the given name and value is automatically added to the QObject, but false is still returned. This means that a return of false can't be used to determine whether a particular property was actually set, unless you know in advance that the property already exists in the QObject.

Note that dynamic properties are added on a per instance basis, i.e., they are added to QObject, not QMetaObject. A property can be removed from an instance by passing the property name and an invalid QVariant value to QObject::setProperty(). The default constructor for QVariant constructs an invalid QVariant.

Dynamic properties can be queried with QObject::property(), just like properties declared at compile time with Q_PROPERTY().

Properties and Custom Types

Custom types used by properties need to be registered using the Q_DECLARE_METATYPE() macro so that their values can be stored in QVariant objects. This makes them suitable for use with both static properties declared using the Q_PROPERTY() macro in class definitions and dynamic properties created at run-time.

Adding Additional Information to a Class

Connected to the property system is an additional macro, Q_CLASSINFO(), that can be used to attach additional name--value pairs to a class's meta-object, for example:

 Q_CLASSINFO("Version", "3.0.0")

Like other meta-data, class information is accessible at run-time through the meta-object; see QMetaObject::classInfo() for details.

See also Meta-Object System, Signals and Slots, Q_DECLARE_METATYPE(), QMetaType, and QVariant.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt 4.5.1