[ fromfile: reflection.xml id: qmetatype ]
We have added custom enumerated types to the QVariant system, through the use of the Q_ENUMS
macro.
It is also possible to add value types of our own to the QMetaType list using the macro Q_DECLARE_METATYPE(MyType)
.
If MyType has public default and copy constructors and a public destructor, the Q_DECLARE_METATYPE
macro enables it to be used as a custom type in QVariant.
In Example 12.13, we introduce a new value type, Fraction
to the known metatypes of the program that contains its definition.
Placing the macro in the header file below the class definition is standard practice.
Example 12.13. src/metatype/fraction.h
A registered metatype must be already declared with Q_DECLARE_METATYPE
.
The template function qRegisterMetaType<T>()
registers the type T
and returns the internal ID used by QMetaType.
The call to this function must occur early in the main program, before any attempt is made to use the registered type in a dynamic way.
When a metatype is declared, it is possible to store a value in a QVariant.
Example 12.14 shows how to store and get declared metatype values back from a QVariant.
Example 12.14. src/metatype/metatype.cpp
[ . . . . ] int main (int argc, char* argv[]) { QApplication app(argc, argv); qRegisterMetaType<Fraction>("Fraction"); Fraction twoThirds (2,3); QVariant var; var.setValue(twoThirds); Q_ASSERT (var.value<Fraction>() == twoThirds); Fraction oneHalf (1,2); Fraction threeQuarters (3,4); qDebug() << "QList<Fraction> to QVariant and back." QList<Fraction> fractions; fractions << oneHalf << twoThirds << threeQuarters; QFile binaryTestFile("testMetaType.bin"); binaryTestFile.open(QIODevice::WriteOnly); QDataStream dout(&binaryTestFile); dout << fractions; binaryTestFile.close(); binaryTestFile.open(QIODevice::ReadOnly); QDataStream din(&binaryTestFile); QList<Fraction> frac2; din >> frac2; binaryTestFile.close(); Q_ASSERT(fractions == frac2); createTest(); qDebug() << "If this output appears, all tests passed."; }
Values of a registered type can be constructed dynamically via QMetaType::construct()
, as shown in Example 12.15.
Example 12.15. src/metatype/metatype.cpp
QMetaType::construct()
returns a void
pointer, so we use reinterpret_cast
to convert it to a Fraction pointer.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |