QMetaType 类

QMetaType 类管理元对象系统中命名类型。 更多...

头: #include <QMetaType>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

注意: 此类的所有函数 thread-safe .

公共类型

enum Type { Void, Bool, Int, UInt, Double, …, UnknownType }
enum TypeFlag { NeedsConstruction, NeedsDestruction, RelocatableType, IsEnumeration, IsUnsignedEnumeration, …, IsConst }
flags TypeFlags

公共函数

  QMetaType (int typeId )
qsizetype alignOf () const
QPartialOrdering compare (const void * lhs , const void * rhs ) const
void * construct (void * where , const void * copy = nullptr) const
void * create (const void * copy = nullptr) const
bool debugStream (QDebug & dbg , const void * rhs )
void destroy (void * data ) const
void destruct (void * data ) const
bool equals (const void * lhs , const void * rhs ) const
QMetaType::TypeFlags flags () const
bool hasRegisteredDataStreamOperators () const
bool hasRegisteredDebugStreamOperator () const
int id () const
bool isEqualityComparable () const
bool isOrdered () const
bool isRegistered () const
bool isValid () const
bool load (QDataStream & stream , void * data ) const
const QMetaObject * metaObject () const
const char * name () const
bool save (QDataStream & stream , const void * data ) const
qsizetype sizeOf () const

静态公共成员

bool canConvert (QMetaType fromType , QMetaType toType )
bool canView (QMetaType fromType , QMetaType toType )
bool convert (QMetaType fromType , const void * from , QMetaType toType , void * to )
QMetaType fromName (QByteArrayView typeName )
QMetaType fromType ()
bool hasRegisteredConverterFunction (QMetaType fromType , QMetaType toType )
bool hasRegisteredConverterFunction ()
bool hasRegisteredMutableViewFunction (QMetaType fromType , QMetaType toType )
bool hasRegisteredMutableViewFunction ()
bool isRegistered (int type )
bool registerConverter ()
bool view (QMetaType fromType , void * from , QMetaType toType , void * to )
int qMetaTypeId ()
int qRegisterMetaType (const char * typeName )
int qRegisterMetaType ()
bool operator!= (QMetaType a , QMetaType b )
bool operator== (QMetaType a , QMetaType b )

  Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE ( 容器 )
  Q_DECLARE_METATYPE ( Type )
  Q_DECLARE_OPAQUE_POINTER ( PointerType )
  Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE ( 容器 )
  Q_DECLARE_SMART_POINTER_METATYPE ( SmartPointer )

详细描述

用作帮助程序的类能编组类型在 QVariant 和在队列信号及槽连接中。它将类型名称关联到类型,以便可以在运行时动态创建和销毁它。声明新类型采用 Q_DECLARE_METATYPE () 以使它们可用于 QVariant 和其它基于模板的函数。调用 qRegisterMetaType () 以使类型可用于基于非模板的函数,譬如:队列信号和槽连接。

可以注册具有公共默认构造函数、公共副本构造函数及公共析构函数的任何类或结构。

以下代码分配并销毁实例化的 MyClass :

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

若想要流运算符 operator<<() and operator>>() 工作在 QVariant 对象存储自定义类型,自定义类型必须提供 operator<<() and operator>>() 运算符。

另请参阅 Q_DECLARE_METATYPE (), QVariant::setValue (), QVariant::value (),和 QVariant::fromValue ().

成员类型文档编制

enum QMetaType:: Type

这些内置类型的支持通过 QMetaType :

常量 描述
QMetaType::Void 43 void
QMetaType::Bool 1 bool
QMetaType::Int 2 int
QMetaType::UInt 3 无符号 int
QMetaType::Double 6 double
QMetaType::QChar 7 QChar
QMetaType::QString 10 QString
QMetaType::QByteArray 12 QByteArray
QMetaType::Nullptr 51 std::nullptr_t
QMetaType::VoidStar 31 void *
QMetaType::Long 32 long
QMetaType::LongLong 4 LongLong
QMetaType::Short 33 short
QMetaType::Char 34 char
QMetaType::Char16 56 char16_t
QMetaType::Char32 57 char32_t
QMetaType::ULong 35 unsigned long
QMetaType::ULongLong 5 ULongLong
QMetaType::UShort 36 unsigned short
QMetaType::SChar 40 signed char
QMetaType::UChar 37 unsigned char
QMetaType::Float 38 float
QMetaType::QObjectStar 39 QObject *
QMetaType::QVariant 41 QVariant
QMetaType::QCursor 0x100a QCursor
QMetaType::QDate 14 QDate
QMetaType::QSize 21 QSize
QMetaType::QTime 15 QTime
QMetaType::QVariantList 9 QVariantList
QMetaType::QPolygon 0x1007 QPolygon
QMetaType::QPolygonF 0x1016 QPolygonF
QMetaType::QColor 0x1003 QColor
QMetaType::QColorSpace 0x1017 QColorSpace (introduced in Qt 5.15)
QMetaType::QSizeF 22 QSizeF
QMetaType::QRectF 20 QRectF
QMetaType::QLine 23 QLine
QMetaType::QTextLength 0x100d QTextLength
QMetaType::QStringList 11 QStringList
QMetaType::QVariantMap 8 QVariantMap
QMetaType::QVariantHash 28 QVariantHash
QMetaType::QIcon 0x1005 QIcon
QMetaType::QPen 0x100c QPen
QMetaType::QLineF 24 QLineF
QMetaType::QTextFormat 0x100e QTextFormat
QMetaType::QRect 19 QRect
QMetaType::QPoint 25 QPoint
QMetaType::QUrl 17 QUrl
QMetaType::QRegularExpression 44 QRegularExpression
QMetaType::QDateTime 16 QDateTime
QMetaType::QPointF 26 QPointF
QMetaType::QPalette 0x1004 QPalette
QMetaType::QFont 0x1000 QFont
QMetaType::QBrush 0x1002 QBrush
QMetaType::QRegion 0x1008 QRegion
QMetaType::QBitArray 13 QBitArray
QMetaType::QImage 0x1006 QImage
QMetaType::QKeySequence 0x100b QKeySequence
QMetaType::QSizePolicy 0x2000 QSizePolicy
QMetaType::QPixmap 0x1001 QPixmap
QMetaType::QLocale 18 QLocale
QMetaType::QBitmap 0x1009 QBitmap
QMetaType::QTransform 0x1010 QTransform
QMetaType::QMatrix4x4 0x1011 QMatrix4x4
QMetaType::QVector2D 0x1012 QVector2D
QMetaType::QVector3D 0x1013 QVector3D
QMetaType::QVector4D 0x1014 QVector4D
QMetaType::QQuaternion 0x1015 QQuaternion
QMetaType::QEasingCurve 29 QEasingCurve
QMetaType::QJsonValue 45 QJsonValue
QMetaType::QJsonObject 46 QJsonObject
QMetaType::QJsonArray 47 QJsonArray
QMetaType::QJsonDocument 48 QJsonDocument
QMetaType::QCborValue 53 QCborValue
QMetaType::QCborArray 54 QCborArray
QMetaType::QCborMap 55 QCborMap
QMetaType::QCborSimpleType 52 QCborSimpleType
QMetaType::QModelIndex 42 QModelIndex
QMetaType::QPersistentModelIndex 50 QPersistentModelIndex (introduced in Qt 5.5)
QMetaType::QUuid 30 QUuid
QMetaType::QByteArrayList 49 QByteArrayList
QMetaType::User 65536 用于用户类型的基值
QMetaType::UnknownType 0 这是无效类型 ID。返回它从 QMetaType 为未注册类型

可以注册额外类型,使用 Q_DECLARE_METATYPE ().

另请参阅 type () 和 typeName ().

enum QMetaType:: TypeFlag
flags QMetaType:: TypeFlags

The enum describes attributes of a type supported by QMetaType .

常量 描述
QMetaType::NeedsConstruction 0x1 This type has non-trivial constructors. If the flag is not set instances can be safely initialized with memset to 0.
QMetaType::NeedsDestruction 0x2 This type has a non-trivial destructor. If the flag is not set calls to the destructor are not necessary before discarding objects.
QMetaType::RelocatableType 0x4 An instance of a type having this attribute can be safely moved to a different memory location using memcpy.
QMetaType::IsEnumeration 0x10 This type is an enumeration.
QMetaType::IsUnsignedEnumeration 0x100 If the type is an Enumeration, its underlying type is unsigned.
QMetaType::PointerToQObject 0x8 This type is a pointer to a derived of QObject .
QMetaType::IsPointer 0x800 This type is a pointer to another type.
QMetaType::IsConst 0x2000 Indicates that values of this types are immutable; for instance because they are pointers to const objects.

TypeFlags 类型是 typedef 对于 QFlags <TypeFlag>。它存储 TypeFlag 值的 OR 组合。

成员函数文档编制

[since 5.0] QMetaType:: QMetaType ( int typeId )

构造 QMetaType 对象包含所有信息有关类型 typeId .

该函数在 Qt 5.0 引入。

[since 6.0] qsizetype QMetaType:: alignOf () const

Returns the alignment of the type in bytes (i.e. alignof(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.

该函数在 Qt 6.0 引入。

另请参阅 QMetaType::construct () 和 QMetaType::sizeOf ().

[static] bool QMetaType:: canConvert ( QMetaType fromType , QMetaType toType )

返回 true if QMetaType::convert can convert from fromType to toType .

The following conversions are supported by Qt:

类型 自动铸造成
QMetaType::Bool QMetaType::QChar , QMetaType::Double , QMetaType::Int , QMetaType::LongLong , QMetaType::QString , QMetaType::UInt , QMetaType::ULongLong
QMetaType::QByteArray QMetaType::Double , QMetaType::Int , QMetaType::LongLong , QMetaType::QString , QMetaType::UInt , QMetaType::ULongLong , QMetaType::QUuid
QMetaType::QChar QMetaType::Bool , QMetaType::Int , QMetaType::UInt , QMetaType::LongLong , QMetaType::ULongLong
QMetaType::QColor QMetaType::QString
QMetaType::QDate QMetaType::QDateTime , QMetaType::QString
QMetaType::QDateTime QMetaType::QDate , QMetaType::QString , QMetaType::QTime
QMetaType::Double QMetaType::Bool , QMetaType::Int , QMetaType::LongLong , QMetaType::QString , QMetaType::UInt , QMetaType::ULongLong
QMetaType::QFont QMetaType::QString
QMetaType::Int QMetaType::Bool , QMetaType::QChar , QMetaType::Double , QMetaType::LongLong , QMetaType::QString , QMetaType::UInt , QMetaType::ULongLong
QMetaType::QKeySequence QMetaType::Int , QMetaType::QString
QMetaType::QVariantList QMetaType::QStringList (if the list's items can be converted to QStrings)
QMetaType::LongLong QMetaType::Bool , QMetaType::QByteArray , QMetaType::QChar , QMetaType::Double , QMetaType::Int , QMetaType::QString , QMetaType::UInt , QMetaType::ULongLong
QMetaType::QPoint QMetaType::QPointF
QMetaType::QRect QMetaType::QRectF
QMetaType::QString QMetaType::Bool , QMetaType::QByteArray , QMetaType::QChar , QMetaType::QColor , QMetaType::QDate , QMetaType::QDateTime , QMetaType::Double , QMetaType::QFont , QMetaType::Int , QMetaType::QKeySequence , QMetaType::LongLong , QMetaType::QStringList , QMetaType::QTime , QMetaType::UInt , QMetaType::ULongLong , QMetaType::QUuid
QMetaType::QStringList QMetaType::QVariantList , QMetaType::QString (if the list contains exactly one item)
QMetaType::QTime QMetaType::QString
QMetaType::UInt QMetaType::Bool , QMetaType::QChar , QMetaType::Double , QMetaType::Int , QMetaType::LongLong , QMetaType::QString , QMetaType::ULongLong
QMetaType::ULongLong QMetaType::Bool , QMetaType::QChar , QMetaType::Double , QMetaType::Int , QMetaType::LongLong , QMetaType::QString , QMetaType::UInt
QMetaType::QUuid QMetaType::QByteArray , QMetaType::QString

Casting between primitive type (int, float, bool etc.) is supported.

Converting between pointers of types derived from QObject will also return true for this function if a qobject_cast from the type described by fromType to the type described by toType would succeed.

A cast from a sequential container will also return true for this function if the toType is QVariantList .

Similarly, a cast from an associative container will also return true for this function the toType is QVariantHash or QVariantMap .

另请参阅 convert (), QSequentialIterable , Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE (), QAssociativeIterable ,和 Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE ().

[static] bool QMetaType:: canView ( QMetaType fromType , QMetaType toType )

返回 true if QMetaType::view can create a mutable view of type toType on type fromType .

Converting between pointers of types derived from QObject will return true for this function if a qobject_cast from the type described by fromType to the type described by toType would succeed.

You can create a mutable view of type QSequentialIterable on any container registered with Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE ().

Similarly you can create a mutable view of type QAssociativeIterable on any container registered with Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE ().

另请参阅 convert (), QSequentialIterable , Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE (), QAssociativeIterable ,和 Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE ().

[since 6.0] QPartialOrdering QMetaType:: compare (const void * lhs , const void * rhs ) const

比较对象在 lhs and rhs for ordering.

返回 QPartialOrdering::Unordered if comparison is not supported or the values are unordered. Otherwise, returns QPartialOrdering::Less , QPartialOrdering::Equivalent or QPartialOrdering::Greater if lhs is less than, equivalent to or greater than rhs ,分别。

Both objects must be of the type described by this metatype. If either lhs or rhs is nullptr , the values are unordered. Comparison is only supported if the type's less than operator was visible to the metatype declaration.

If the type's equality operator was also visible, values will only compare equal if the equality operator says they are. In the absence of an equality operator, when neither value is less than the other, values are considered equal; if equality is also available and two such values are not equal, they are considered unordered, just as NaN (not a number) values of a floating point type lie outside its ordering.

注意: If no less than operator was visible to the metatype declaration, values are unordered even if an equality operator visible to the declaration considers them equal: compare() == 0 only agrees with equals () if the less than operator was visible.

该函数在 Qt 6.0 引入。

另请参阅 equals () 和 isOrdered ().

[since 5.0] void *QMetaType:: construct ( void * where , const void * copy = nullptr) 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 ,并返回 where 。若 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).

该函数在 Qt 5.0 引入。

[static, since 5.2] bool QMetaType:: convert ( QMetaType fromType , const void * from , QMetaType toType , void * to )

Converts the object at from from fromType to the preallocated space at to typed toType 。返回 true ,若转换成功,否则 false。

Both from and to have to be valid pointers.

该函数在 Qt 5.2 引入。

[since 5.0] void *QMetaType:: create (const void * copy = nullptr) const

Returns a copy of copy , assuming it is of the type that this QMetaType instance was created for. If copy is nullptr ,创建默认构造实例。

该函数在 Qt 5.0 引入。

另请参阅 QMetaType::destroy ().

[since 5.2] bool QMetaType:: debugStream ( QDebug & dbg , const void * rhs )

Streams the object at rhs to the debug stream dbg 。返回 true 当成功时,否则 false。

该函数在 Qt 5.2 引入。

[since 5.0] void QMetaType:: destroy ( void * data ) const

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

该函数在 Qt 5.0 引入。

另请参阅 QMetaType::create ().

[since 5.0] 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.

该函数在 Qt 5.0 引入。

另请参阅 QMetaType::construct ().

[since 6.0] bool QMetaType:: equals (const void * lhs , const void * rhs ) const

比较对象在 lhs and rhs for equality.

Both objects must be of the type described by this metatype. Can only compare the two objects if a less than or equality operator for the type was visible to the metatype declaration. Otherwise, the metatype never considers values equal. When an equality operator was visible to the metatype declaration, it is authoritative; otherwise, if less than is visible, when neither value is less than the other, the two are considered equal. If values are unordered (see compare () for details) they are not equal.

Returns true if the two objects compare equal, otherwise false.

该函数在 Qt 6.0 引入。

另请参阅 isEqualityComparable () 和 compare ().

[since 5.0] QMetaType::TypeFlags QMetaType:: flags () const

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

该函数在 Qt 5.0 引入。

另请参阅 QMetaType::TypeFlags and QMetaType::flags().

[static] QMetaType QMetaType:: fromName ( QByteArrayView typeName )

返回 QMetaType matching typeName . The returned object is not valid if the typeName is not known to QMetaType

[static, since 5.15] template <typename T> QMetaType QMetaType:: fromType ()

返回 QMetaType corresponding to the type in the template parameter.

该函数在 Qt 5.15 引入。

[static, since 5.2] bool QMetaType:: hasRegisteredConverterFunction ( QMetaType fromType , QMetaType toType )

返回 true , if the meta type system has a registered conversion from meta type id fromType to toType

该函数在 Qt 5.2 引入。

[static, since 5.2] template <typename From, typename To> bool QMetaType:: hasRegisteredConverterFunction ()

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

这是重载函数。

该函数在 Qt 5.2 引入。

[since 6.1] bool QMetaType:: hasRegisteredDataStreamOperators () const

返回 true , if the meta type system has registered data stream operators for this meta type.

该函数在 Qt 6.1 引入。

[since 6.0] bool QMetaType:: hasRegisteredDebugStreamOperator () const

返回 true , if the meta type system has a registered debug stream operator for this meta type.

该函数在 Qt 6.0 引入。

[static, since 5.2] bool QMetaType:: hasRegisteredMutableViewFunction ( QMetaType fromType , QMetaType toType )

返回 true , if the meta type system has a registered mutable view on meta type id fromType of meta type id toType .

该函数在 Qt 5.2 引入。

[static, since 6.0] template <typename From, typename To> bool QMetaType:: hasRegisteredMutableViewFunction ()

返回 true , if the meta type system has a registered mutable view on type From of type To.

这是重载函数。

该函数在 Qt 6.0 引入。

[since 5.13] int QMetaType:: id () const

Returns id type hold by this QMetatype instance.

该函数在 Qt 5.13 引入。

bool QMetaType:: isEqualityComparable () const

返回 true if a less than or equality operator for the type described by this metatype was visible to the metatype declaration, otherwise false .

另请参阅 equals () 和 isOrdered ().

bool QMetaType:: isOrdered () const

返回 true if a less than operator for the type described by this metatype was visible to the metatype declaration, otherwise false .

另请参阅 compare () 和 isEqualityComparable ().

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

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

另请参阅 type (), typeName (),和 Type .

[since 5.0] bool QMetaType:: isRegistered () const

返回 true 若此 QMetaType object contains valid information about a type, false otherwise.

该函数在 Qt 5.0 引入。

[since 5.0] bool QMetaType:: isValid () const

返回 true 若此 QMetaType object contains valid information about a type, false otherwise.

该函数在 Qt 5.0 引入。

bool QMetaType:: load ( QDataStream & stream , void * data ) const

Reads the object of this type from the given stream into data 。返回 true if the object is loaded successfully; otherwise returns false .

The type must have been registered with Q_DECLARE_METATYPE () 事先。

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

另请参阅 save ().

[since 5.5] const QMetaObject *QMetaType:: metaObject () const

return a QMetaObject relative to this type.

If the type is a pointer type to a subclass of QObject , flags () contains QMetaType::PointerToQObject and this function returns the corresponding QMetaObject . This can be used to in combinaison with QMetaObject::construct to create QObject of this type.

If the type is a Q_GADGET , flags () contains QMetaType::IsGadget , and this function returns its QMetaObject . This can be used to retrieve QMetaMethod and QMetaProperty and use them on a pointer of this type. (given by QVariant::data for example)

If the type is an enumeration, flags () contains QMetaType::IsEnumeration , and this function returns the QMetaObject of the enclosing object if the enum was registered as a Q_ENUM or nullptr otherwise

该函数在 Qt 5.5 引入。

另请参阅 QMetaType::flags ().

[since 5.15] const char *QMetaType:: name () const

Returns the type name associated with this QMetaType , or a null pointer if no matching type was found. The returned pointer must not be deleted.

该函数在 Qt 5.15 引入。

另请参阅 typeName ().

[static, since 5.2] template <typename From, typename To> bool QMetaType:: registerConverter ()

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.


					

该函数在 Qt 5.2 引入。

bool QMetaType:: save ( QDataStream & stream , const void * data ) const

Writes the object pointed to by data 到给定 stream 。返回 true if the object is saved successfully; otherwise returns false .

The type must have been registered with Q_DECLARE_METATYPE () 事先。

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

另请参阅 load ().

[since 5.0] qsizetype 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.

该函数在 Qt 5.0 引入。

另请参阅 QMetaType::construct (), QMetaType::sizeOf(), and QMetaType::alignOf ().

[static, since 6.0] bool QMetaType:: view ( QMetaType fromType , void * from , QMetaType toType , void * to )

Creates a mutable view on the object at from of fromType in the preallocated space at to typed toType 。返回 true if the conversion succeeded, otherwise false.

该函数在 Qt 6.0 引入。

相关非成员

template <typename T> 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.

典型用法:

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.

另请参阅 Q_DECLARE_METATYPE () 和 QMetaType::type ().

template <typename T> int qRegisterMetaType (const char * typeName )

注册类型名称 typeName 为类型 T 。返回的内部 ID 用于 QMetaType 。可以注册拥有公共默认构造函数、公共副本构造函数和公共析构函数的任何类 (或结构)。

此函数要求 T 是在函数被调用时的完全定义类型。对于指针类型,它还要求指向完全定义的类型。使用 Q_DECLARE_OPAQUE_POINTER () 能够注册指向转发声明类型的指针。

在已注册类型后,可以在运行时动态创建和销毁该类型的对象。

此范例注册类 MyClass :

qRegisterMetaType<MyClass>("MyClass");
					

此函数对注册 typedef 很有用,因此它们可以用于 QMetaProperty ,或在 QueuedConnections

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

警告: 此函数仅适用于注册别名 (typedef) 为每种其它用例 Q_DECLARE_METATYPE and qMetaTypeId () 应该被使用以取而代之。

另请参阅 isRegistered () 和 Q_DECLARE_METATYPE ().

template <typename T> int qRegisterMetaType ()

调用此函数去注册类型 T . T 必须被声明采用 Q_DECLARE_METATYPE ()。返回元类型 ID。

范例:

int id = qRegisterMetaType<MyStruct>();
					

此函数要求 T 是在函数被调用时的完全定义类型。对于指针类型,它还要求指向完全定义的类型。使用 Q_DECLARE_OPAQUE_POINTER () 能够注册指向转发声明类型的指针。

在已注册类型后,可以在运行时动态创建和销毁该类型的对象。

要使用类型 T in QVariant ,使用 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 采用 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() 函数。

另请参阅 Q_DECLARE_METATYPE ().

[since 5.15] bool operator!= ( QMetaType a , QMetaType b )

这是重载函数。

返回 true QMetaType a represents a different type than the QMetaType b ,否则返回 false .

该函数在 Qt 5.15 引入。

[since 5.15] bool operator== ( QMetaType a , QMetaType b )

这是重载函数。

返回 true QMetaType a represents the same type as the QMetaType b ,否则返回 false .

该函数在 Qt 5.15 引入。

宏文档编制

Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE ( 容器 )

This macro makes the container 容器 知道 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 )

此宏使类型 Type 知道 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 .

此宏要求 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.

此范例展示 Q_DECLARE_METATYPE() 的典型用例:

struct MyStruct
{
    int i;
    ...
};
Q_DECLARE_METATYPE(MyStruct)
					

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

namespace MyNamespace
{
    ...
}
Q_DECLARE_METATYPE(MyNamespace::MyStruct)
					

由于 MyStruct 现在知道 QMetaType ,它可以用于 QVariant :

MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant
...
// retrieve the value
MyStruct s2 = var.value<MyStruct>();
					

Some types are registered automatically and do not need this macro:

注意: This method also registers the stream and debug operators for the type if they are visible at registration time. As this is done automatically in some places, it is strongly recommended to declare the stream operators for a type directly after the type itself. Because of the argument dependent lookup rules of C++, it is also strongly recommended to declare the operators in the same namespace as the type itself.

The stream operators should have the following signatures:

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

另请参阅 qRegisterMetaType ().

[since 5.0] Q_DECLARE_OPAQUE_POINTER ( PointerType )

This macro enables pointers to forward-declared types ( PointerType ) to be registered with QMetaType 使用 Q_DECLARE_METATYPE () 或 qRegisterMetaType ().

该函数在 Qt 5.0 引入。

另请参阅 Q_DECLARE_METATYPE () 和 qRegisterMetaType ().

Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE ( 容器 )

This macro makes the container 容器 知道 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 )

此宏使智能指针 SmartPointer 知道 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 .

注意, 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'.
    }
}