Important: Please read the Qt Code of Conduct -

[Pretty much Solved] A good place to put qRegisterMetaType?

  • Given that main() or something called from main() directly is not an option.

    Is qRegisterMetaType fast enough that I can simply call it when constructing the class? Or is there a very fast lookup function that can check whether the metatype is registered?

  • Lifetime Qt Champion


    It depends on the use case, but I usually put this call in the constructor of the classes that will use the metatype unless this class is instantiated at high rates. In that case I use an initialization function that does the work (but it seems that it's not an option in your case)

    Hope it helps

  • So if multiple classes use this one class, I might have my registration code all over the place.

    I think I should try harder to get access to a one-time initializer function.


  • @
    template <typename Type> class MetaTypeRegistration
    inline MetaTypeRegistration()

    Put a <code>static MetaTypeRegistration<YourType> registration;</code> in the <code>.cpp</code> file implementing <code>YourType</code>.

    This way your metatype will be registered once at startup, and the registration is close by the implementation and does not require to modify <code>main</code>.

    If you are using those metatypes during static initialization time make sure you don't run into the static initialization fiasco.

  • Lukas,

    if it's that easy, why isn't there an official Qt method of doing it that way?

  • Moderators

    another possibility would be (since templates are a bit of a overhead for the compiler):
    void registerMetaTypes()
    static bool registered = false;
    if( !registered )
    registered = true;

  • [quote author="Asperamanca" date="1367907144"]...if it's that easy, why isn't there an official Qt method of doing it that way?[/quote]Well, maybe because it is that easy to do on your own. ;-)

    In addition you won't find this pattern in Qt because you don't find this pattern in Qt. And there is the potential that you shoot yourself in the foot if you use the metatype at static initialization time and don't mind static initialization order.

    But feel free to file a change request and see what the Qt Project is thinking (all code I post here is public domain and can be used freely without any restrictions).

    [quote author="raven-worx" date="1367907902"]...another possibility would be (since templates are a bit of a overhead for the compiler)...[/quote]There is indeed a compile time overhead to templates, but it is negligible in this case. Your solution has again the downside of seperating the definition and registration (which means I could do the registration in <code>main</code> anyway).

  • [[blank-post-content-placeholder]]

Log in to reply