QMetaType::Type from template type

1.4k views Asked by At

Is it possible to determine QMetaType::Type value of a template argument.

I tried this:

template <class T>
class MyClass {
public:
    int getType() {
        return QMetaType::type(typeid(T).name());
    }
};

But this returns always 0 (QMetaType::UnknownType) because Qt uses different type names than the compiler.

It should work like the following:

MyClass<int>().getType();     // 2 (QMetaType::Int)
MyClass<QString>().getType(); // 10 (QMetaType::QString)
MyClass<QRect>().getType();   // 19 (QMetaType::QRect)
MyClass<MyType>().getType();  // 1024 (Set by qRegisterMetaType)
1

There are 1 answers

0
Alexander A. On

I tested your code on Qt 5.12.4 and it seems to work. You could also Q_DECLARE_METATYPE to register your custom type and then use qMetaTypeId() to get the metaType id.

Here my test code and example:

#include <QCoreApplication>
#include <QDebug>
#include <QMetaType>
#include <QRect>
#include <QMetaObject>

class MyType
{
public:
    int _member;
};
// needed for getType2()
Q_DECLARE_METATYPE(MyType);
// needed for getType()
const int id = qRegisterMetaType<MyType>("MyType");

template <class T>
class MyClass {
public:
    int getType() {
        return QMetaType::type(typeid(T).name());
    }
    int getType2() {
        return qMetaTypeId<T>();
    }

};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << MyClass<int>().getType();
    qDebug() << MyClass<QString>().getType();
    qDebug() << MyClass<QRect>().getType();
    qDebug() << MyClass<MyType>().getType();

    qDebug() << MyClass<int>().getType2();
    qDebug() << MyClass<QString>().getType2();
    qDebug() << MyClass<QRect>().getType2();
    qDebug() << MyClass<MyType>().getType2();

    return a.exec();
}

this outputs:

2
10
19
1024
2
10
19
1024