12.6.  MetaTypes, Declaring and Registering

[ fromfile: reflection.xml id: qmetatype ]

Example 12.13. src/metatype/fraction.h

[ . . . . ]
class Fraction : public QPair<qint32, qint32> {
public:
    Fraction(qint32 n = 0, qint32 d = 1) : QPair<qint32,qint32>(n,d)
    { }
};

Q_DECLARE_METATYPE(Fraction);
[ . . . . ]

qRegisterMetaType()

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.";
}

Example 12.15. src/metatype/metatype.cpp

[ . . . . ]

void createTest() {
    static int fracType = QMetaType::type("Fraction");
    void* vp = QMetaType::construct(fracType);
    Fraction* fp = reinterpret_cast<Fraction*>(vp); 1
    fp->first = 1;
    fp->second = 2;
    Q_ASSERT(*fp == Fraction(1,2));
}

1

Note: This is our first use of reinterpret_cast in this book!