QMetaType Class

The QMetaType class manages named types in the meta-object system. More...

Header: #include <QMetaType>
qmake: QT += core

Note: All functions in this class are thread-safe.

Public Types

enum Type { Void, Bool, Int, UInt, ..., UnknownType }
enum TypeFlag { NeedsConstruction, NeedsDestruction, MovableType }
flags TypeFlags

Public Functions

QMetaType(const int typeId)
~QMetaType()
void * construct(void * where, const void * copy = 0) const
void * create(const void * copy = 0) const
void destroy(void * data) const
void destruct(void * data) const
TypeFlags flags() const
bool isRegistered() const
bool isValid() const
int sizeOf() const

Static Public Members

bool compare(const void * lhs, const void * rhs, int typeId, int * result)
void * construct(int type, void * where, const void * copy)
bool convert(const void * from, int fromTypeId, void * to, int toTypeId)
void * create(int type, const void * copy = 0)
bool debugStream(QDebug & dbg, const void * rhs, int typeId)
void destroy(int type, void * data)
void destruct(int type, void * where)
bool hasRegisteredComparators()
bool hasRegisteredComparators(int typeId)
bool hasRegisteredConverterFunction(int fromTypeId, int toTypeId)
bool hasRegisteredConverterFunction()
bool hasRegisteredDebugStreamOperator()
bool hasRegisteredDebugStreamOperator(int typeId)
bool isRegistered(int type)
bool load(QDataStream & stream, int type, void * data)
const QMetaObject * metaObjectForType(int type)
bool registerComparators()
bool registerConverter()
bool registerConverter(MemberFunction function)
bool registerConverter(MemberFunctionOk function)
bool registerConverter(UnaryFunction function)
bool registerDebugStreamOperator()
bool save(QDataStream & stream, int type, const void * data)
int sizeOf(int type)
int type(const char * typeName)
TypeFlags typeFlags(int type)
const char * typeName(int typeId)

Related Non-Members

int qMetaTypeId()
int qRegisterMetaType(const char * typeName)
int qRegisterMetaType()
void qRegisterMetaTypeStreamOperators(const char * typeName)

Macros

Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE( Container)
Q_DECLARE_METATYPE( Type)
Q_DECLARE_OPAQUE_POINTER( PointerType)
Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE( Container)
Q_DECLARE_SMART_POINTER_METATYPE( SmartPointer)

Detailed Description

The QMetaType class manages named types in the meta-object system.

The class is used as a helper to marshall types in QVariant and in queued signals and slots connections. It associates a type name to a type so that it can be created and destructed dynamically at run-time. Declare new types with Q_DECLARE_METATYPE() to make them available to QVariant and other template-based functions. Call qRegisterMetaType() to make type available to non-template based functions, such as the queued signal and slot connections.

Any class or struct that has a public default constructor, a public copy constructor, and a public destructor can be registered.

The following code allocates and destructs an instance of MyClass:

int id = QMetaType::type("MyClass");
if (id != QMetaType::UnknownType) {
    void *myClassPtr = QMetaType::create(id);
    ...
    QMetaType::destroy(id, myClassPtr);
    myClassPtr = 0;
}

If we want the stream operators operator<<() and operator>>() to work on QVariant objects that store custom types, the custom type must provide operator<<() and operator>>() operators.

See also Q_DECLARE_METATYPE(), QVariant::setValue(), QVariant::value(), and QVariant::fromValue().

Member Type Documentation

enum QMetaType::Type

These are the built-in types supported by QMetaType:

ConstantValueDescription
QMetaType::Void43void
QMetaType::Bool1bool
QMetaType::Int2int
QMetaType::UInt3unsigned int
QMetaType::Double6double
QMetaType::QChar7QChar
QMetaType::QString10QString
QMetaType::QByteArray12QByteArray
QMetaType::VoidStar31void *
QMetaType::Long32long
QMetaType::LongLong4LongLong
QMetaType::Short33short
QMetaType::Char34char
QMetaType::ULong35unsigned long
QMetaType::ULongLong5ULongLong
QMetaType::UShort36unsigned short
QMetaType::SChar40signed char
QMetaType::UChar37unsigned char
QMetaType::Float38float
QMetaType::QObjectStar39QObject *
QMetaType::QVariant41QVariant
QMetaType::QCursor74QCursor
QMetaType::QDate14QDate
QMetaType::QSize21QSize
QMetaType::QTime15QTime
QMetaType::QVariantList9QVariantList
QMetaType::QPolygon71QPolygon
QMetaType::QPolygonF86QPolygonF
QMetaType::QColor67QColor
QMetaType::QSizeF22QSizeF
QMetaType::QRectF20QRectF
QMetaType::QLine23QLine
QMetaType::QTextLength77QTextLength
QMetaType::QStringList11QStringList
QMetaType::QVariantMap8QVariantMap
QMetaType::QVariantHash28QVariantHash
QMetaType::QIcon69QIcon
QMetaType::QPen76QPen
QMetaType::QLineF24QLineF
QMetaType::QTextFormat78QTextFormat
QMetaType::QRect19QRect
QMetaType::QPoint25QPoint
QMetaType::QUrl17QUrl
QMetaType::QRegExp27QRegExp
QMetaType::QRegularExpression44QRegularExpression
QMetaType::QDateTime16QDateTime
QMetaType::QPointF26QPointF
QMetaType::QPalette68QPalette
QMetaType::QFont64QFont
QMetaType::QBrush66QBrush
QMetaType::QRegion72QRegion
QMetaType::QBitArray13QBitArray
QMetaType::QImage70QImage
QMetaType::QKeySequence75QKeySequence
QMetaType::QSizePolicy121QSizePolicy
QMetaType::QPixmap65QPixmap
QMetaType::QLocale18QLocale
QMetaType::QBitmap73QBitmap
QMetaType::QMatrix79QMatrix
QMetaType::QTransform80QTransform
QMetaType::QMatrix4x481QMatrix4x4
QMetaType::QVector2D82QVector2D
QMetaType::QVector3D83QVector3D
QMetaType::QVector4D84QVector4D
QMetaType::QQuaternion85QQuaternion
QMetaType::QEasingCurve29QEasingCurve
QMetaType::QJsonValue45QJsonValue
QMetaType::QJsonObject46QJsonObject
QMetaType::QJsonArray47QJsonArray
QMetaType::QJsonDocument48QJsonDocument
QMetaType::QModelIndex42QModelIndex
QMetaType::QUuid30QUuid
QMetaType::User1024Base value for user types
QMetaType::UnknownType0This is an invalid type id. It is returned from QMetaType for types that are not registered

Additional types can be registered using Q_DECLARE_METATYPE().

See also type() and typeName().

enum QMetaType::TypeFlag
flags QMetaType::TypeFlags

The enum describes attributes of a type supported by QMetaType.

ConstantValueDescription
QMetaType::NeedsConstruction0x1This type has non-trivial constructors. If the flag is not set instances can be safely initialized with memset to 0.
QMetaType::NeedsDestruction0x2This type has a non-trivial destructor. If the flag is not set calls to the destructor are not necessary before discarding objects.
QMetaType::MovableType0x4An instance of a type having this attribute can be safely moved by memcpy.

The TypeFlags type is a typedef for QFlags<TypeFlag>. It stores an OR combination of TypeFlag values.

Member Function Documentation

QMetaType::QMetaType(const int typeId)

Constructs a QMetaType object that contains all information about type typeId.

This function was introduced in Qt 5.0.

QMetaType::~QMetaType()

Destructs this object.

bool QMetaType::compare(const void * lhs, const void * rhs, int typeId, int * result) [static]

Compares the objects at lhs and rhs. Both objects need to be of type typeId. result is set to less than, equal to or greater than zero, if lhs is less than, equal to or greater than rhs. Returns true, if the comparison succeeded, otherwiess false.

This function was introduced in Qt 5.2.

void * QMetaType::construct(int type, void * where, const void * copy) [static]

Constructs a value of the given type in the existing memory addressed by where, that is a copy of copy, and returns where. If copy is zero, the value is default constructed.

This is a low-level function for explicitly managing the memory used to store the type. Consider calling create() if you don't need this level of control (that is, use "new" rather than "placement new").

You must ensure that where points to a location that can store a value of type type, and that where is suitably aligned. The type's size can be queried by calling sizeOf().

The rule of thumb for alignment is that a type is aligned to its natural boundary, which is the smallest power of 2 that is bigger than the type, unless that alignment is larger than the maximum useful alignment for the platform. For practical purposes, alignment larger than 2 * sizeof(void*) is only necessary for special hardware instructions (e.g., aligned SSE loads and stores on x86).

This function was introduced in Qt 5.0.

See also destruct() and sizeOf().

void * QMetaType::construct(void * where, const void * copy = 0) const

Constructs a value of the type that this QMetaType instance was constructed for in the existing memory addressed by where, that is a copy of copy, and returns where. If copy is zero, the value is default constructed.

This is a low-level function for explicitly managing the memory used to store the type. Consider calling create() if you don't need this level of control (that is, use "new" rather than "placement new").

You must ensure that where points to a location where the new value can be stored and that where is suitably aligned. The type's size can be queried by calling sizeOf().

The rule of thumb for alignment is that a type is aligned to its natural boundary, which is the smallest power of 2 that is bigger than the type, unless that alignment is larger than the maximum useful alignment for the platform. For practical purposes, alignment larger than 2 * sizeof(void*) is only necessary for special hardware instructions (e.g., aligned SSE loads and stores on x86).

This function was introduced in Qt 5.0.

bool QMetaType::convert(const void * from, int fromTypeId, void * to, int toTypeId) [static]

Converts the object at from from fromTypeId to the preallocated space at to typed toTypeId. Returns true, if the conversion succeeded, otherwise false.

This function was introduced in Qt 5.2.

void * QMetaType::create(int type, const void * copy = 0) [static]

Returns a copy of copy, assuming it is of type type. If copy is zero, creates a default constructed instance.

See also destroy(), isRegistered(), and Type.

void * QMetaType::create(const void * copy = 0) const

Returns a copy of copy, assuming it is of the type that this QMetaType instance was created for. If copy is null, creates a default constructed instance.

This function was introduced in Qt 5.0.

See also QMetaType::destroy().

bool QMetaType::debugStream(QDebug & dbg, const void * rhs, int typeId) [static]

Streams the object at rhs of type typeId to the debug stream dbg. Returns true on success, otherwise false.

This function was introduced in Qt 5.2.

void QMetaType::destroy(int type, void * data) [static]

Destroys the data, assuming it is of the type given.

See also create(), isRegistered(), and Type.

void QMetaType::destroy(void * data) const

Destroys the data, assuming it is of the type that this QMetaType instance was created for.

This function was introduced in Qt 5.0.

See also QMetaType::create().

void QMetaType::destruct(int type, void * where) [static]

Destructs the value of the given type, located at where.

Unlike destroy(), this function only invokes the type's destructor, it doesn't invoke the delete operator.

This function was introduced in Qt 5.0.

See also construct().

void QMetaType::destruct(void * data) const

Destructs the value, located at data, assuming that it is of the type for which this QMetaType instance was constructed for.

Unlike destroy(), this function only invokes the type's destructor, it doesn't invoke the delete operator.

This function was introduced in Qt 5.0.

See also QMetaType::construct().

TypeFlags QMetaType::flags() const

Returns flags of the type for which this QMetaType instance was constructed.

This function was introduced in Qt 5.0.

See also QMetaType::TypeFlags and QMetaType::typeFlags().

bool QMetaType::hasRegisteredComparators() [static]

Returns true, if the meta type system has registered comparators for type T.

This function was introduced in Qt 5.2.

bool QMetaType::hasRegisteredComparators(int typeId) [static]

Returns true, if the meta type system has registered comparators for type id typeId.

This function was introduced in Qt 5.2.

bool QMetaType::hasRegisteredConverterFunction(int fromTypeId, int toTypeId) [static]

Returns true, if the meta type system has a registered conversion from meta type id fromTypeId to toTypeId

This function was introduced in Qt 5.2.

bool QMetaType::hasRegisteredConverterFunction() [static]

Returns true, if the meta type system has a registered conversion from type From to type To.

This is an overloaded function.

This function was introduced in Qt 5.2.

bool QMetaType::hasRegisteredDebugStreamOperator() [static]

Returns true, if the meta type system has a registered debug stream operator for type T.

This function was introduced in Qt 5.2.

bool QMetaType::hasRegisteredDebugStreamOperator(int typeId) [static]

Returns true, if the meta type system has a registered debug stream operator for type id typeId.

This function was introduced in Qt 5.2.

bool QMetaType::isRegistered(int type) [static]

Returns true if the datatype with ID type is registered; otherwise returns false.

See also type(), typeName(), and Type.

bool QMetaType::isRegistered() const

Returns true if this QMetaType object contains valid information about a type, false otherwise.

This function was introduced in Qt 5.0.

bool QMetaType::isValid() const

Returns true if this QMetaType object contains valid information about a type, false otherwise.

This function was introduced in Qt 5.0.

bool QMetaType::load(QDataStream & stream, int type, void * data) [static]

Reads the object of the specified type from the given stream into data. Returns true if the object is loaded successfully; otherwise returns false.

The type must have been registered with qRegisterMetaType() and qRegisterMetaTypeStreamOperators() beforehand.

Normally, you should not need to call this function directly. Instead, use QVariant's operator>>(), which relies on load() to stream custom types.

See also save() and qRegisterMetaTypeStreamOperators().

const QMetaObject * QMetaType::metaObjectForType(int type) [static]

Returns QMetaObject of a given type, if the type is a pointer to type derived from QObject.

This function was introduced in Qt 5.0.

bool QMetaType::registerComparators() [static]

Registers comparison operetarors for the user-registered type T. This requires T to have both an operator== and an operator<. Returns true if the registration succeeded, otherwise false.

This function was introduced in Qt 5.2.

bool QMetaType::registerConverter() [static]

Registers the possibility of an implicit conversion from type From to type To in the meta type system. Returns true if the registration succeeded, otherwise false.

This function was introduced in Qt 5.2.

bool QMetaType::registerConverter(MemberFunction function) [static]

This is an overloaded function.

Registers a method function like To From::function() const as converter from type From to type To in the meta type system. Returns true if the registration succeeded, otherwise false.

This function was introduced in Qt 5.2.

bool QMetaType::registerConverter(MemberFunctionOk function) [static]

This is an overloaded function.

Registers a method function like To From::function(bool *ok) const as converter from type From to type To in the meta type system. Returns true if the registration succeeded, otherwise false.

This function was introduced in Qt 5.2.

bool QMetaType::registerConverter(UnaryFunction function) [static]

This is an overloaded function.

Registers a unary function object function as converter from type From to type To in the meta type system. Returns true if the registration succeeded, otherwise false.

This function was introduced in Qt 5.2.

bool QMetaType::registerDebugStreamOperator() [static]

Registers the debug stream operator for the user-registered type T. This requires T to have an operator<<(QDebug dbg, T). Returns true if the registration succeeded, otherwise false.

bool QMetaType::save(QDataStream & stream, int type, const void * data) [static]

Writes the object pointed to by data with the ID type to the given stream. Returns true if the object is saved successfully; otherwise returns false.

The type must have been registered with qRegisterMetaType() and qRegisterMetaTypeStreamOperators() beforehand.

Normally, you should not need to call this function directly. Instead, use QVariant's operator<<(), which relies on save() to stream custom types.

See also load() and qRegisterMetaTypeStreamOperators().

int QMetaType::sizeOf(int type) [static]

Returns the size of the given type in bytes (i.e. sizeof(T), where T is the actual type identified by the type argument).

This function is typically used together with construct() to perform low-level management of the memory used by a type.

This function was introduced in Qt 5.0.

See also construct().

int QMetaType::sizeOf() const

Returns the size of the type in bytes (i.e. sizeof(T), where T is the actual type for which this QMetaType instance was constructed for).

This function is typically used together with construct() to perform low-level management of the memory used by a type.

This function was introduced in Qt 5.0.

See also QMetaType::construct() and QMetaType::sizeOf().

int QMetaType::type(const char * typeName) [static]

Returns a handle to the type called typeName, or QMetaType::UnknownType if there is no such type.

See also isRegistered(), typeName(), and Type.

TypeFlags QMetaType::typeFlags(int type) [static]

Returns flags of the given type.

This function was introduced in Qt 5.0.

See also QMetaType::TypeFlags.

const char * QMetaType::typeName(int typeId) [static]

Returns the type name associated with the given typeId, or 0 if no matching type was found. The returned pointer must not be deleted.

See also type(), isRegistered(), and Type.

Related Non-Members

int qMetaTypeId()

Returns the meta type id of type T at compile time. If the type was not declared with Q_DECLARE_METATYPE(), compilation will fail.

Typical usage:

int id = qMetaTypeId<QString>();    // id is now QMetaType::QString
id = qMetaTypeId<MyStruct>();       // compile error if MyStruct not declared

QMetaType::type() returns the same ID as qMetaTypeId(), but does a lookup at runtime based on the name of the type. QMetaType::type() is a bit slower, but compilation succeeds if a type is not registered.

Note: This function is thread-safe.

This function was introduced in Qt 4.1.

See also Q_DECLARE_METATYPE() and QMetaType::type().

int qRegisterMetaType(const char * typeName)

Registers the type name typeName for the type T. Returns the internal ID used by QMetaType. Any class or struct that has a public default constructor, a public copy constructor and a public destructor can be registered.

This function requires that T is a fully defined type at the point where the function is called. For pointer types, it also requires that the pointed to type is fully defined. Use Q_DECLARE_OPAQUE_POINTER() to be able to register pointers to forward declared types.

After a type has been registered, you can create and destroy objects of that type dynamically at run-time.

This example registers the class MyClass:

qRegisterMetaType<MyClass>("MyClass");

This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections

typedef QString CustomString;
qRegisterMetaType<CustomString>("CustomString");

Warning: This function is useful only for registering an alias (typedef) for every other use case Q_DECLARE_METATYPE and qMetaTypeId() should be used instead.

Note: This function is thread-safe.

See also qRegisterMetaTypeStreamOperators(), QMetaType::isRegistered(), and Q_DECLARE_METATYPE().

int qRegisterMetaType()

Call this function to register the type T. T must be declared with Q_DECLARE_METATYPE(). Returns the meta type Id.

Example:

int id = qRegisterMetaType<MyStruct>();

This function requires that T is a fully defined type at the point where the function is called. For pointer types, it also requires that the pointed to type is fully defined. Use Q_DECLARE_OPAQUE_POINTER() to be able to register pointers to forward declared types.

After a type has been registered, you can create and destroy objects of that type dynamically at run-time.

To use the type T in QVariant, using Q_DECLARE_METATYPE() is sufficient. To use the type T in queued signal and slot connections, qRegisterMetaType<T>() must be called before the first connection is established.

Also, to use type T with the QObject::property() API, qRegisterMetaType<T>() must be called before it is used, typically in the constructor of the class that uses T, or in the main() function.

Note: This function is thread-safe.

This function was introduced in Qt 4.2.

See also Q_DECLARE_METATYPE().

void qRegisterMetaTypeStreamOperators(const char * typeName)

Registers the stream operators for the type T called typeName.

Afterward, the type can be streamed using QMetaType::load() and QMetaType::save(). These functions are used when streaming a QVariant.

qRegisterMetaTypeStreamOperators<MyClass>("MyClass");

The stream operators should have the following signatures:

QDataStream &operator<<(QDataStream &out, const MyClass &myObj);
QDataStream &operator>>(QDataStream &in, MyClass &myObj);

Note: This function is thread-safe.

See also qRegisterMetaType(), QMetaType::isRegistered(), and Q_DECLARE_METATYPE().

Macro Documentation

Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE( Container)

This macro makes the container Container known to QMetaType as an associative container. This makes it possible to put an instance of Container<T, U> into a QVariant, if T and U are themselves known to QMetaType.

Note that all of the Qt associative containers already have built-in support, and it is not necessary to use this macro with them. The std::map container also has built-in support.

This example shows a typical use of Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE():

#include <unordered_list>

Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE(std::unordered_map)

void someFunc()
{
    std::unordered_map<int, bool> container;
    QVariant var = QVariant::fromValue(container);
    // ...
}

Q_DECLARE_METATYPE( Type)

This macro makes the type Type known to QMetaType as long as it provides a public default constructor, a public copy constructor and a public destructor. It is needed to use the type Type as a custom type in QVariant.

This macro requires that Type is a fully defined type at the point where it is used. For pointer types, it also requires that the pointed to type is fully defined. Use in conjunction with Q_DECLARE_OPAQUE_POINTER() to register pointers to forward declared types.

Ideally, this macro should be placed below the declaration of the class or struct. If that is not possible, it can be put in a private header file which has to be included every time that type is used in a QVariant.

Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections or in QObject's property system, you also have to call qRegisterMetaType() since the names are resolved at runtime.

This example shows a typical use case of Q_DECLARE_METATYPE():

struct MyStruct
{
    int i;
    ...
};

Q_DECLARE_METATYPE(MyStruct)

If MyStruct is in a namespace, the Q_DECLARE_METATYPE() macro has to be outside the namespace:

namespace MyNamespace
{
    ...
}

Q_DECLARE_METATYPE(MyNamespace::MyStruct)

Since MyStruct is now known to QMetaType, it can be used in QVariant:

MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant

...

// retrieve the value
MyStruct s2 = var.value<MyStruct>();

See also qRegisterMetaType().

Q_DECLARE_OPAQUE_POINTER( PointerType)

This macro enables pointers to forward-declared types (PointerType) to be registered with QMetaType using either Q_DECLARE_METATYPE() or qRegisterMetaType().

This function was introduced in Qt 5.0.

See also Q_DECLARE_METATYPE() and qRegisterMetaType().

Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE( Container)

This macro makes the container Container known to QMetaType as a sequential container. This makes it possible to put an instance of Container<T> into a QVariant, if T itself is known to QMetaType.

Note that all of the Qt sequential containers already have built-in support, and it is not necessary to use this macro with them. The std::vector and std::list containers also have built-in support.

This example shows a typical use of Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE():

#include <deque>

Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE(std::deque)

void someFunc()
{
    std::deque<QFile*> container;
    QVariant var = QVariant::fromValue(container);
    // ...
}

Q_DECLARE_SMART_POINTER_METATYPE( SmartPointer)

This macro makes the smart pointer SmartPointer known to QMetaType as a smart pointer. This makes it possible to put an instance of SmartPointer<T> into a QVariant, if T is a type which inherits QObject.

Note that the QWeakPointer, QSharedPointer and QPointer already have built-in support, and it is not necessary to use this macro with them.

This example shows a typical use of Q_DECLARE_SMART_POINTER_METATYPE():

#include <memory>

Q_DECLARE_SMART_POINTER_METATYPE(std::shared_ptr)

void someFunc()
{
    auto smart_ptr = std::make_shared<QFile>();
    QVariant var = QVariant::fromValue(smart_ptr);
    // ...
    if (var.canConvert<QObject*>()) {
        QObject *sp = var.value<QObject*>();
        qDebug() << sp->metaObject()->className(); // Prints 'QFile'.
    }
}
Notes provided by the Qt Community

No notes