DataObject: An Extension of QObject
DataObject An Extension of QObject
We have developed an extension to QObject named DataObject that we can use as a base class for other data types that require any of the following features:
- A virtual interface for obtaining properties, MetaProperties, and metaClass information
- Convenience functions for copying and comparing property values of DataObjects
- A toString() function that returns a presentation of all the properties of the object in XML format
This improved interface makes DataObject a Façade for QObject.
DataObject, shown in Figure 15.3, is used in several forthcoming examples to demonstrate various design patterns.
Figure 15.3. DataObject
DataObject is Qt-property aware and takes advantage of this interface for reading and writing properties of arbitrary QObjects, as shown in Example 15.7.
Example 15.7. src/libs/dataobjects/dataobject.cpp
[ . . . . ] bool DataObject::readFrom(const QObject& source) { bool retval = true; const QMetaObject* meta = source.metaObject(); int count = meta->propertyCount(); for (int i=0; Iproperty(i); const char* pname = metap.name(); if (metap.isWritable()) { retval = setProperty(pname, source.property(pname)) && retval; } } return retval; } [ . . . . ] bool DataObject::writeTo(QObject& dest) const { bool result = true; foreach (QString propname, propertyNames()) { if (metaProperty(propname).isWritable()) { QVariant val = property(propname); result = dest.setProperty(propname.toAscii(), val) && result; } } return result; } |
Exercises: Meta Objects, Properties, and Reflective Programming
1. |
Many people have several pets, each of which require periodic maintenance (visits to the veterinarian, immunizations, vitamins, grooming, etc.).
|
2. |
Do the exercise in Section 25.1. |
Property Containers PropsMap
|