And so a QVariant instantiation silently registeres a (previously declared) metatype

207 Views Asked by At

Take this program (adapted from an exploratory test-case, where I noticed that a custom metatype bahaves as if it was registered, although qRegisterMetaType had not been called):

#include <QMetaType>
#include <QVariant>

#include <iostream>

class C1 {
};

Q_DECLARE_METATYPE(C1)


int main() {
    std::cout << QMetaType::type("C1") << std::endl;

    QVariant v = QVariant::fromValue<C1>(C1());

    std::cout << QMetaType::type("C1") << std::endl;

    return 0;
}

This outputs:

0
256

(and further tests do show that the metatype is indeed registered -- it can be construct'ed (even in places where Q_DECLARE_METATYPE(..) is not visible), etc)

Is this behaviour well-known? Relied on? (Probably not, but attempting to get a failing test following the "official" rule to register a metatype first got me puzzled, hence the question)

P.S. Of course, one can see qRegisterMetaType called within Q_DECLARE_METATYPE(..), but the question still holds (at least I would like it to).

Thanks in advance.

1

There are 1 best solutions below

0
On

Q_DECLARE_METATYPE doesn't call qRegisterMetaType, it defines a function that does. But QVariant::fromValue<C1> calls qRegisterMetaType indirectly, by calling the previously defined function.

The documentation suggests that calling qRegisterMetaType is only needed for things like queued connections.

Which means that you don't need to call qRegisterMetaType before using QVariant template functions for your type (but Q_DECLARE_METATYPE has to be called in each compilation unit where those template functions are used or the compilation will fail).