15.2. QMetaObject: The MetaObject Pattern
By
A class that has a MetaObject supports reflection . This is a feature found in many object-oriented languages. It does not exist in C++, but Qt's MetaObject compiler ( moc ) generates the code to support this for desired classes. As long as certain conditions apply, [3] each class derived from QObject will have a QMetaObject generated for it by moc , as shown in Figure 15.2. QObject has a member function that returns a pointer to the object's QMetaObject .
Figure 15.2. MetaObjects
QMetaObject* QObject::metaObject () const [virtual] A QMetaObject can be used to invoke functions such as:
The signal and slot mechanism also relies on the QMetaObject .
By using the
QMetaObject
and
QMetaProperty
, it is possible to write code that is generic enough to handle all
|
15.3. Type Identification and qobject_cast
RTTI
, or
Run-Time Type Identification
, as its
In addition to C++'s RTTI operators, dynamic_cast and typeid (Section 19.8), Qt provides two mechanisms for run-time type identification.
qobject_cast
is an ANSI-style
DestType * qobject_cast< DestType *> ( QObject * qoptr ) A typecast operator converts an expression from one type to another, following certain rules and restrictions imposed by the types and the language. Like other cast operators, qobject_cast takes the destination type as a template parameter. It returns a different-typed pointer to the same object. If at runtime the actual pointer type cannot be converted to DestType* , then the conversion fails and the value returned is NULL .
As the signature suggests,
qobject_cast
is type-restricted to arguments of type
DestType *
, where
DestType
is derived from
QObject
and the class was fully
In situations where you have base class pointers to derived class objects,
Example 15.1. src/qtrtti/myapp-classdef.cpp
Because
qApp
always points to the currently running
QApplication
, this function will return
QString imagePath(QString filename) {
MyApplication* app = MyApplication::instance();
QString path = app->imagesURL() + "/" + filename;
<-- 1
return path;
}
Note
QObject
also offers a Java-style
Example 15.2 shows some client code that uses inherits() . Example 15.2. src/qtrtti/qtrtti.cpp
|

C++ GUI Programming with Qt 4 (2nd Edition) (Prentice Hall Open Source Software Development Series)

Design Patterns: Elements of Reusable Object-Oriented Software

Modern C++ Design: Generic Programming and Design Patterns Applied

Advanced Qt Programming: Creating Great Software with C++ and Qt 4 (Prentice Hall Open Source Software Development)