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:

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.).

  • Derive a class named Pet from DataObject. Supply this class with appropriate attributes that can uniquely describe the pet (type, breed, name, ID, birthday, etc.). For each attribute, you will need a getter and a setter so that you can set up a Q_PROPERTY.
  • Derive another class from DataObject that you can call Maintenance (if you can't think of a better name). This class should have attributes that uniquely describe a particular maintenance event (type of event, date, cost, etc.). Maintenance objects will be stored as children of Pet objects.
  • Derive a PetList class from DataObject.Pet objects will be children of PetList.
  • Serialization is facilitated by the DataObject::toString() function. Find out how to use this for your PetWriter class and how to reverse the action in your PetReader class.
  • Design a nice GUI for these classes so that the user can enter, store, and display data.
2.

Do the exercise in Section 25.1.

Property Containers PropsMap

Категории