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.).
|
2. |
Do the exercise in Section 25.1. |
Property Containers PropsMap |
Part I: Introduction to C++ and Qt 4
C++ Introduction
Classes
Introduction to Qt
Lists
Functions
Inheritance and Polymorphism
Part II: Higher-Level Programming
Libraries
Introduction to Design Patterns
QObject
Generics and Containers
Qt GUI Widgets
Concurrency
Validation and Regular Expressions
Parsing XML
Meta Objects, Properties, and Reflective Programming
More Design Patterns
Models and Views
Qt SQL Classes
Part III: C++ Language Reference
Types and Expressions
Scope and Storage Class
Statements and Control Structures
Memory Access
Chapter Summary
Inheritance in Detail
Miscellaneous Topics
Part IV: Programming Assignments
MP3 Jukebox Assignments
Part V: Appendices
MP3 Jukebox Assignments
Bibliography
MP3 Jukebox Assignments