QMetaType Class

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

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

该类可等价比较

注意:该类中的所有函数都是线程安全的

公共类型

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

公共函数

(since 6.0) QMetaType()
QMetaType(int typeId)
(since 6.0) qsizetype alignOf() const
(since 6.0) 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
(since 6.0) bool equals(const void *lhs, const void *rhs) const
QMetaType::TypeFlags flags() const
(since 6.1) bool hasRegisteredDataStreamOperators() const
(since 6.0) bool hasRegisteredDebugStreamOperator() const
int id() const
(since 6.5) bool isCopyConstructible() const
(since 6.5) bool isDefaultConstructible() const
(since 6.5) bool isDestructible() const
bool isEqualityComparable() const
(since 6.5) bool isMoveConstructible() 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
(since 6.5) void registerType() const
bool save(QDataStream &stream, const void *data) const
qsizetype sizeOf() const
(since 6.6) QMetaType underlyingType() 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)
(since 6.0) bool hasRegisteredMutableViewFunction()
bool isRegistered(int type)
bool registerConverter()
bool registerConverter(To (From::*)() const function)
bool registerConverter(To (From::*)(bool *) const function)
bool registerConverter(UnaryFunction function)
(since 6.0) bool registerMutableView(To (From::*)() function)
(since 6.0) bool registerMutableView(UnaryFunction function)
(since 6.0) bool view(QMetaType fromType, void *from, QMetaType toType, void *to)
(since 6.4) size_t qHash(QMetaType key, size_t seed = 0)
int qMetaTypeId()
int qRegisterMetaType()
(since 6.5) int qRegisterMetaType(QMetaType meta)
bool operator!=(const QMetaType &lhs, const QMetaType &rhs)
(since 6.5) QDebug operator<<(QDebug d, QMetaType m)
bool operator==(const QMetaType &lhs, const QMetaType &rhs)

详细说明

该类用于在QVariant 以及队列信号和插槽连接中作为辅助工具来 marshall 类型。该类将类型名称与类型关联,以便在运行时动态创建和销毁类型。

可以使用qRegisterMetaType() 或registerType() 向 QMetaType 注册类型名。大多数操作都不需要注册;只有尝试将字符串形式的类型名解析为 QMetaType 对象或类型 ID 的操作才需要注册。这些操作包括使用QObject::connect() 的旧式信号槽连接、从QDataStream 读取用户类型到QVariant ,或绑定到其他语言和 IPC 机制,如 QML、D-Bus、JavaScript 等。

下面的代码根据MyClass 的名称分配和析构一个实例,这要求MyClass 之前已经注册过:

QMetaType type = QMetaType::fromName("MyClass");
if (type.isValid()) {
    void *myClassPtr = type.create();
    ...
    type.destroy(myClassPtr);
    myClassPtr = nullptr;
}

如果我们希望流运算符operator<<()operator>>() 能在存储自定义类型的QVariant 对象上工作,自定义类型必须提供operator<<()operator>>() 运算符。

另请参见 Q_DECLARE_METATYPE()、QVariant::setValue()、QVariant::value() 和QVariant::fromValue()。

成员类型文档

enum QMetaType::Type

这些是QMetaType 支持的内置类型:

常量描述
QMetaType::Void43void
QMetaType::Bool1bool
QMetaType::Int2int
QMetaType::UInt3unsigned int
QMetaType::Double6double
QMetaType::QChar7QChar
QMetaType::QString10字符串
QMetaType::QByteArray12字节数组
QMetaType::Nullptr51std::nullptr_t
QMetaType::VoidStar31void *
QMetaType::Long32long
QMetaType::LongLong4长龙
QMetaType::Short33short
QMetaType::Char34char
QMetaType::Char1656char16_t
QMetaType::Char3257char32_t
QMetaType::ULong35unsigned long
QMetaType::ULongLong5超长
QMetaType::UShort36unsigned short
QMetaType::SChar40signed char
QMetaType::UChar37unsigned char
QMetaType::Float38float
QMetaType::Float1663qfloat16
QMetaType::QObjectStar39QObject *
QMetaType::QCursor0x100a游标
QMetaType::QDate14日期
QMetaType::QSize21QSize
QMetaType::QTime15时间
QMetaType::QVariantList9变量列表
QMetaType::QPolygon0x1007多边形
QMetaType::QPolygonF0x1016QPolygonF
QMetaType::QColor0x1003颜色
QMetaType::QColorSpace0x1017QColorSpace(在 Qt 5.15 中引入)
QMetaType::QSizeF22QSizeF
QMetaType::QRectF20QRectF
QMetaType::QLine23QLine
QMetaType::QTextLength0x100dQTextLength
QMetaType::QStringList11QStringList
QMetaType::QVariantMap8QVariantMap
QMetaType::QVariantHash28QVariantHash
QMetaType::QVariantPair58QVariantPair
QMetaType::QIcon0x1005图标
QMetaType::QPen0x100c
QMetaType::QLineF24QLineF
QMetaType::QTextFormat0x100e文本格式
QMetaType::QRect19QRect
QMetaType::QPoint25QPoint
QMetaType::QUrl17QUrl
QMetaType::QRegularExpression44QRegularExpression
QMetaType::QDateTime16QDateTime
QMetaType::QPointF26QPointF
QMetaType::QPalette0x1004QPalette
QMetaType::QFont0x1000QFont
QMetaType::QBrush0x1002QBrush
QMetaType::QRegion0x1008QRegion
QMetaType::QBitArray13QBitArray
QMetaType::QImage0x1006Q 图像
QMetaType::QKeySequence0x100bQKeySequence
QMetaType::QSizePolicy0x2000QSizePolicy
QMetaType::QPixmap0x1001QPixmap
QMetaType::QLocale18QLocale
QMetaType::QBitmap0x1009QBitmap
QMetaType::QTransform0x1010QTransform
QMetaType::QMatrix4x40x1011QMatrix4x4
QMetaType::QVector2D0x1012QVector2D
QMetaType::QVector3D0x1013QVector3D
QMetaType::QVector4D0x1014QVector4D
QMetaType::QQuaternion0x1015四元数
QMetaType::QEasingCurve29QEasingCurve
QMetaType::QJsonValue45QJsonValue
QMetaType::QJsonObject46QJsonObject
QMetaType::QJsonArray47QJsonArray
QMetaType::QJsonDocument48QJsonDocument
QMetaType::QCborValue53QCborValue
QMetaType::QCborArray54QCborArray
QMetaType::QCborMap55QCborMap
QMetaType::QCborSimpleType52QCborSimpleType
QMetaType::QModelIndex42QModelIndex
QMetaType::QPersistentModelIndex50QPersistentModelIndex(在 Qt 5.5 中引入)
QMetaType::QUuid30QUuid
QMetaType::QByteArrayList49QByteArrayList
QMetaType::QVariant41QVariant 变量
QMetaType::User65536用户类型的基本值
QMetaType::UnknownType0这是一个无效的类型 ID。对于未注册的类型,它将从QMetaType 返回。

可以使用qRegisterMetaType() 或调用registerType() 注册其他类型。

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

枚举 QMetaType::TypeFlag
flags QMetaType::TypeFlags

该枚举描述了QMetaType 支持的类型的属性。

常量描述
QMetaType::NeedsConstruction0x1该类型有一个默认构造函数。如果未设置该标志,则可以使用 memset 将实例初始化为 0。
QMetaType::NeedsCopyConstruction (since Qt 6.5)0x4000该类型有一个非繁琐的复制构造函数。如果未设置该标志,则可以使用 memcpy 复制实例。
QMetaType::NeedsMoveConstruction (since Qt 6.5)0x8000该类型有一个非繁琐的移动构造函数。如果未设置标记,则可以使用 memcpy 移动实例。
QMetaType::NeedsDestruction0x2该类型有一个非繁琐的析构函数。如果未设置该标记,则在丢弃对象前无需调用析构函数。
QMetaType::RelocatableType0x4具有此属性的类型实例可以使用 memcpy 安全地移动到不同的内存位置。
QMetaType::IsEnumeration0x10该类型是一个枚举。
QMetaType::IsUnsignedEnumeration0x100如果是枚举类型,其底层类型为无符号类型。
QMetaType::PointerToQObject0x8该类型是指向从QObject 派生的类的指针。
QMetaType::IsPointer0x800该类型是指向另一类型的指针。
QMetaType::IsConst0x2000表示该类型的值是不可变的;例如,因为它们是指向常量对象的指针。

注意: 在 Qt 6.5 之前,如果拷贝 construtor 或析构函数是非琐碎的(也就是说,如果类型不是琐碎的),NeedsConstruction 和 NeedsDestruction 标志都会被错误地设置。

请注意,Needs 标志可能被设置,但元类型可能没有相关类型的可公开访问的构造函数或可公开访问的析构函数。

TypeFlags 类型是QFlags<TypeFlag> 的类型定义。它存储 TypeFlag 值的 OR 组合。

成员函数文档

[constexpr noexcept, since 6.0] QMetaType::QMetaType()

构造一个默认的、无效的 QMetaType 对象。

该函数在 Qt 6.0 中引入。

[explicit] QMetaType::QMetaType(int typeId)

构造一个 QMetaType 对象,其中包含有关typeId 类型的所有信息。

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

以字节为单位返回类型的对齐方式(即 alignof(T),其中 T 是该QMetaType 实例的实际类型)。

该函数通常与construct() 一起使用,对类型使用的内存进行底层管理。

该函数在 Qt 6.0 中引入。

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

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

如果QMetaType::convert 可以将fromType 转换为toType ,则返回true 。请注意,这主要是指执行转换的能力,而实际转换在尝试时可能会失败(例如,将浮点数值转换为超出其范围的整数)。

registerConverter() 函数可用于注册其他转换,可以是内置类型与非内置类型之间的转换,也可以是两个非内置类型之间的转换。如果转换路径已注册,该函数将返回true

Qt 支持以下转换:

类型自动转换为
QMetaType::BoolQMetaType::QChar,QMetaType::Double,QMetaType::Int,QMetaType::LongLong,QMetaType::QString,QMetaType::UIntQMetaType::ULongLong
QMetaType::QByteArrayQMetaType::Double,QMetaType::Int,QMetaType::LongLong,QMetaType::QString,QMetaType::UInt,QMetaType::ULongLongQMetaType::QUuid
QMetaType::QCharQMetaType::Bool,QMetaType::Int,QMetaType::UInt,QMetaType::LongLongQMetaType::ULongLong
QMetaType::QColorQMetaType::QString
QMetaType::QDateQMetaType::QDateTime,QMetaType::QString
QMetaType::QDateTimeQMetaType::QDate,QMetaType::QStringQMetaType::QTime
QMetaType::DoubleQMetaType::Bool,QMetaType::Int,QMetaType::LongLong,QMetaType::QString,QMetaType::UIntQMetaType::ULongLong
QMetaType::QFontQMetaType::QString
QMetaType::IntQMetaType::Bool,QMetaType::QChar,QMetaType::Double,QMetaType::LongLong,QMetaType::QString,QMetaType::UIntQMetaType::ULongLong
QMetaType::QKeySequenceQMetaType::Int,QMetaType::QString
QMetaType::QVariantListQMetaType::QStringList (如果列表项可以转换为 QStrings)
QMetaType::LongLongQMetaType::Bool,QMetaType::QByteArray,QMetaType::QChar,QMetaType::Double,QMetaType::Int,QMetaType::QString,QMetaType::UIntQMetaType::ULongLong
QMetaType::QPointQMetaType::QPointF
QMetaType::QRectQMetaType::QRectF
QMetaType::QStringQMetaType::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::ULongLongQMetaType::QUuid
QMetaType::QStringListQMetaType::QVariantList,QMetaType::QString (如果列表正好包含一个项目)
QMetaType::QTimeQMetaType::QString
QMetaType::UIntQMetaType::Bool,QMetaType::QChar,QMetaType::Double,QMetaType::Int,QMetaType::LongLong,QMetaType::QStringQMetaType::ULongLong
QMetaType::ULongLongQMetaType::Bool,QMetaType::QChar,QMetaType::Double,QMetaType::Int,QMetaType::LongLong,QMetaType::QStringQMetaType::UInt
QMetaType::QUuidQMetaType::QByteArray,QMetaType::QString

其他支持的转换包括所有基元类型(int,float,bool 等,包括所有枚举)之间的转换,以及任何指针类型和std::nullptr_t 之间的转换。枚举也可以转换为QStringQByteArray

如果fromTypetoType 都是从QObject 派生的类型(或指向它们的指针),那么如果其中一个类型是从另一个派生的,则此函数也将返回true 。也就是说,如果static_cast<> 可以从fromType 描述的类型编译到toType 描述的类型,则返回 true。convert() 函数的操作类似于qobject_cast() ,它验证QVariant 所指向对象的动态类型。

如果toTypeQVariantList ,则从顺序容器进行的转置也会返回 true。

同样,如果toTypeQVariantHashQVariantMap ,则从关联容器进行的转置也会为该函数返回 true。

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

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

如果QMetaType::view 可以在fromType 上创建toType 类型的可变视图,则返回true

QObject 派生类型的指针之间进行转换时,如果从fromType 所描述的类型到toType 所描述的类型的qobject_cast 转换成功,则此函数将返回 true。

您可以在任何通过Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE() 注册的容器上创建QSequentialIterable 类型的可变视图。

同样,您也可以在任何以Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE() 注册的容器上创建QAssociativeIterable 类型的可变视图。

另请参阅 convert(),QSequentialIterable,Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE(),QAssociativeIterableQ_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE().

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

比较lhsrhs 中的对象是否排序。

如果不支持比较或值未排序,则返回QPartialOrdering::Unordered 。否则,如果lhs 小于、等于或大于rhs ,则分别返回QPartialOrdering::LessQPartialOrdering::EquivalentQPartialOrdering::Greater

两个对象都必须是本元类型所描述的类型。如果lhsrhsnullptr ,则值是无序的。只有在元类型声明中可见类型的小于操作符时,才支持比较。

如果该类型的相等运算符也是可见的,那么只有当相等运算符表示值相等时,才会比较它们是否相等。在没有相等运算符的情况下,当两个值都不小于另一个值时,值被认为是相等的;如果也有相等运算符,但两个值不相等,它们被认为是无序的,就像浮点类型的 NaN(非数字)值不在其排序范围内一样。

注意: 如果元类型声明中没有小于运算符,即使声明中可见的相等运算符认为两个值相等,它们也是无序的:compare() == 0 只有在小于运算符可见时才与equals() 一致。

此功能在 Qt 6.0 中引入。

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

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

where 所寻址的现有内存中构造一个与QMetaType 实例类型相同的值,该值是copy 的副本,并返回where 。如果copy 为零,则默认构造值。

这是一个低级函数,用于明确管理用于存储该类型的内存。如果不需要这种级别的控制,可以考虑调用create() (也就是说,使用 "new "而不是 "placement new")。

必须确保where 指向可以存储新值的位置,并且where 适当对齐。类型的大小可以通过调用sizeOf() 查询。

对齐的经验法则是,除非对齐方式大于平台的最大有效对齐方式,否则类型应按其自然边界对齐,即大于类型的 2 的最小幂次对齐。在实际应用中,只有特殊硬件指令(例如 x86 上对齐的 SSE 加载和存储)才需要大于 2 * sizeof(void*) 的对齐方式。

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

from 中的对象从fromType 转换到to 类型toType 中的预分配空间。如果转换成功,则返回true ,否则返回 false。

fromto 都必须是有效的指针。

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

返回copy 的副本,假定它与此QMetaType 实例的创建类型相同。如果copynullptr ,则会创建一个默认构造的实例。

另请参阅 QMetaType::destroy()。

bool QMetaType::debugStream(QDebug &dbg, const void *rhs)

rhs 中的对象串流到调试流dbg 。成功时返回true ,否则返回 false。

void QMetaType::destroy(void *data) const

销毁data ,前提是该QMetaType 实例是为此类型创建的。

另请参阅 QMetaType::create().

void QMetaType::destruct(void *data) const

析构位于data 的值,假定该值属于构建QMetaType 实例的类型。

destroy() 不同,该函数只调用类型的析构函数,而不调用删除操作符。

另请参见 QMetaType::construct()。

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

比较lhsrhs 中的对象是否相等。

两个对象必须都属于该元类型所描述的类型。只有在元类型声明中可见该类型的小于或相等运算符时,才能比较两个对象。否则,元类型永远不会认为两个值相等。如果在元类型声明中可见相等运算符,则该运算符具有权威性;否则,如果可见小于运算符,当两个值都不小于另一个值时,这两个值被视为相等。如果值是无序的(详见compare() ),它们就不相等。

如果两个对象比较后相等,则返回 true,否则返回 false。

此函数在 Qt 6.0 中引入。

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

[constexpr] QMetaType::TypeFlags QMetaType::flags() const

返回构建QMetaType 实例的类型标志。要检查特定的类型特征,最好使用 "is-"函数而不是直接使用 flags。

另请参阅 QMetaType::TypeFlags, QMetaType::flags(),isDefaultConstructible(),isCopyConstructible(),isMoveConstructible(),isDestructible(),isEqualityComparable(), 和isOrdered().

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

返回与typeName 匹配的QMetaType 。如果类型名称不为QMetaType

[static constexpr] template <typename T> QMetaType QMetaType::fromType()

返回与模板参数中的类型相对应的QMetaType

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

返回true ,如果元类型系统已注册从元类型 idfromTypetoType

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

如果元类型系统已注册从类型 From 到类型 To 的转换,则返回true

这是一个重载函数。

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

如果元类型系统为该元类型注册了数据流操作符,则返回true

此函数在 Qt 6.1 中引入。

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

如果元类型系统为该元类型注册了调试流操作符,则返回true

此函数在 Qt 6.0 中引入。

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

如果元类型系统在元类型 idfromType 的元类型 idtoType 上注册了可变视图,则返回true

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

如果元类型系统对 To 类型的 From 类型注册了可变视图,则返回true

这是一个重载函数。

此函数在 Qt 6.0 中引入。

int QMetaType::id() const

返回此 QMetatype 实例持有的 id 类型。

[noexcept, since 6.5] bool QMetaType::isCopyConstructible() const

如果该类型可以复制构造,则返回 true。如果可以,则construct() 和create() 可以与非空的copy 参数一起使用。

此函数在 Qt 6.5 中引入。

另请参阅 flags()、isDefaultConstructible()、isMoveConstructible() 和isDestructible()。

[noexcept, since 6.5] bool QMetaType::isDefaultConstructible() const

如果该类型可以默认构造,则返回 true。如果可以,则construct() 和create() 可以与空的copy 参数一起使用。

此函数在 Qt 6.5 中引入。

另请参阅 flags()、isCopyConstructible()、isMoveConstructible() 和isDestructible()。

[noexcept, since 6.5] bool QMetaType::isDestructible() const

如果该类型可以被销毁,则返回 true。如果可以,则可以调用destroy() 和destruct() 。

此函数在 Qt 6.5 中引入。

另请参阅 flags()、isDefaultConstructible()、isCopyConstructible() 和isMoveConstructible()。

bool QMetaType::isEqualityComparable() const

如果元类型声明中可见该元类型所描述类型的小于或相等运算符,则返回true ,否则返回false

另请参见 equals() 和isOrdered()。

[noexcept, since 6.5] bool QMetaType::isMoveConstructible() const

如果此类型可以被移动构造,则返回 true。QMetaType 目前没有使用此特性的 API。

此函数在 Qt 6.5 中引入。

另请参阅 flags()、isDefaultConstructible()、isCopyConstructible() 和isDestructible()。

bool QMetaType::isOrdered() const

如果元类型声明中可见该元类型描述的类型的小于运算符,则返回true ,否则返回false

另请参见 compare() 和isEqualityComparable()。

[noexcept] bool QMetaType::isRegistered() const

如果此QMetaType 对象已在 Qt XML 全局元类型注册表中注册,则返回true 。注册后,可通过名称(使用QMetaType::fromName()) 或 ID(使用构造函数)找到该类型。

另请参阅 qRegisterMetaType() 和isValid()。

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

如果 ID 为type 的数据类型已注册,则返回true ;否则返回false

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

[constexpr noexcept] bool QMetaType::isValid() const

如果QMetaType 对象包含有关类型的有效信息,则返回true ,否则返回 false。

另请参见 isRegistered().

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

将此类型的对象从给定的stream 读入data 。如果对象加载成功,则返回true ;否则返回false

通常情况下,您不需要直接调用此函数。取而代之的是使用QVariantoperator>>() ,它依赖 load() 来流式传输自定义类型。

另请参阅 save() 。

[constexpr] const QMetaObject *QMetaType::metaObject() const

返回相对于该类型的QMetaObject

如果该类型是指向QObject 子类的指针类型,则flags() 包含QMetaType::PointerToQObject ,该函数返回相应的QMetaObject 。该函数可与QMetaObject::newInstance() 结合使用,以创建该类型的 QObject。

如果类型是Q_GADGET ,则flags() 包含QMetaType::IsGadget 。如果类型是指向Q_GADGET 的指针,则flags() 包含QMetaType::PointerToGadget 。在这两种情况下,该函数都会返回其QMetaObject 。这可用于检索QMetaMethodQMetaProperty ,并将它们用于该类型的指针,如QVariant::data() 所示。

如果类型是枚举,flags() 包含QMetaType::IsEnumeration 。在这种情况下,如果枚举被注册为Q_ENUM ,则该函数返回外层对象的QMetaObject ,否则返回nullptr

另请参见 QMetaType::flags()。

[constexpr] const char *QMetaType::name() const

返回与QMetaType 相关联的类型名称,如果没有找到匹配的类型,则返回一个空指针。返回的指针不得删除。

另请参阅 typeName()。

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

在元类型系统中注册从类型 From 到类型 To 的隐式转换可能性。如果注册成功,则返回true ,否则返回 false。

class Counter {
  int number = 0;
public:
  int value() const { return number; }
  operator int() const { return value(); }
  void increment() {++number;}
};
QMetaType::registerConverter<Counter, int>();

[static] template <typename From, typename To> bool QMetaType::registerConverter(To (From::*)() const function)

这是一个重载函数。

function 类似 To From::function() const 的方法注册为元类型系统中从 From 类型到 To 类型的转换器。如果注册成功,则返回true ,否则返回 false。

struct Coordinates {
  int x;
  int y;
  int z;

  QString toString() const { return u"[x: %1; y: %2, z: %3]"_s.arg(QString::number(x),
    QString::number(y),
    QString::number(z)); }
};
QMetaType::registerConverter<Coordinates, QString>(&Coordinates::toString);

[static] template <typename From, typename To> bool QMetaType::registerConverter(To (From::*)(bool *) const function)

这是一个重载函数。

function 类似 To From::function(bool *ok) const 的方法注册为元类型系统中从 From 类型到 To 类型的转换器。如果注册成功,则返回true ,否则返回 false。

函数可以使用ok 指针来指示转换是否成功。

struct BigNumber {
    long long l;

    int toInt(bool *ok = nullptr) const {
      const bool canConvertSafely = l < std::numeric_limits<int>::max();
      if (ok)
        *ok = canConvertSafely;
      return l;
    }
};
QMetaType::registerConverter<BigNumber, int>(&BigNumber::toInt);

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

这是一个重载函数。

在元类型系统中将单值函数对象function 注册为从 From 类型到 To 类型的转换器。如果注册成功,则返回true ,否则返回 false。

function 必须接收 类型的实例,并返回 类型的实例。它可以是函数指针、lambda 或函数对象。自 Qt XML 6.5 起, 也可以返回 的实例,以便能够指示失败的转换。From To function std::optional<To>

QMetaType::registerConverter<CustomStringType, QString>([](const CustomStringType &str) {
    return QString::fromUtf8(str.data());
});
QMetaType::registerConverter<QJsonValue, QPointF>(
          [](const QJsonValue &value) -> std::optional<QPointF> {
    const auto object = value.toObject();
    if (!object.contains("x") || !object.contains("y"))
        return std::nullopt;  // The conversion fails if the required properties are missing
    return QPointF{object["x"].toDouble(), object["y"].toDouble()};
});

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

这是一个重载函数。

将类似To From::function() 的方法function 注册为元类型系统中From 类型上To 类型的可变视图。如果注册成功,则返回true ,否则返回false

此函数在 Qt 6.0 中引入。

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

这是一个重载函数。

在元类型系统中将单值函数对象function 注册为 To 类型的可变视图。如果注册成功,则返回true ,否则返回false

此函数在 Qt 6.0 中引入。

[since 6.5] void QMetaType::registerType() const

使用QMetaType::fromName() 在类型注册表中注册QMetaType ,以便可以通过名称找到它。

该函数在 Qt 6.5 中引入。

另请参见 qRegisterMetaType()。

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

data 指向的对象写入给定的stream 。如果对象保存成功,则返回true ;否则返回false

通常情况下,您不需要直接调用此函数。取而代之的是使用QVariantoperator<<() ,它依赖 save() 来对自定义类型进行流式处理。

另请参阅 load() 。

[constexpr] qsizetype QMetaType::sizeOf() const

以字节为单位返回类型的大小(即 sizeof(T),其中 T 是构建QMetaType 实例的实际类型)。

该函数通常与construct() 一起使用,对类型使用的内存进行底层管理。

另请参见 QMetaType::construct()、QMetaType::sizeOf() 和QMetaType::alignOf()。

[since 6.6] QMetaType QMetaType::underlyingType() const

如果该元类型代表一个枚举,则该方法返回一个数字类的元类型,其符号性和大小与枚举底层类型相同。如果表示QFlags 类型,则返回QMetaType::Int 。在所有其他情况下,将返回一个无效的QMetaType

此函数在 Qt 6.6 中引入。

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

to 类型为toType 的预分配空间中创建fromfromType 对象的可变视图。如果转换成功,则返回true ,否则返回 false。

此函数在 Qt 6.0 中引入。

相关非成员

[since 6.4] size_t qHash(QMetaType key, size_t seed = 0)

返回key 的哈希值,使用seed 作为计算的种子。

此函数在 Qt 6.4 中引入。

[constexpr] template <typename T> int qMetaTypeId()

在编译时返回T 类型的元类型 ID。如果未使用Q_DECLARE_METATYPE() 声明类型,编译将失败。

典型用法:

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

QMetaType::type() 返回的 ID 与 qMetaTypeId() 相同,但会在运行时根据类型名称进行查找。QMetaType::type() 的速度稍慢,但如果类型未注册,编译会成功。

另请参见 Q_DECLARE_METATYPE() 和QMetaType::type()。

[constexpr] template <typename T> int qRegisterMetaType()

调用此函数注册T 类型。返回元类型 ID。

举例说明:

int id = qRegisterMetaType<MyStruct>();

该函数要求T 在调用该函数时是完全定义的类型。对于指针类型,它还要求所指向的类型是完全定义的。使用Q_DECLARE_OPAQUE_POINTER() 可以注册指向前向声明类型的指针。

要在QMetaTypeQVariantQObject::property() API 中使用T 类型,则无需注册。

要在队列信号和插槽连接中使用T 类型,必须在建立第一个连接之前调用qRegisterMetaType<T>() 。这通常在使用T 的类的构造函数或main() 函数中完成。

注册类型后,可以使用QMetaType::fromName() 根据其名称找到它。

另请参见 Q_DECLARE_METATYPE()。

[since 6.5] int qRegisterMetaType(QMetaType meta)

注册元类型meta 并返回其类型 ID。

该函数要求T 在调用该函数时是完全定义的类型。对于指针类型,它还要求指向的类型是完全定义的。使用Q_DECLARE_OPAQUE_POINTER() 可以注册指向前向声明类型的指针。

要在QMetaTypeQVariantQObject::property() API 中使用T 类型,则无需注册。

要在队列信号和插槽连接中使用T 类型,必须在建立第一个连接之前调用qRegisterMetaType<T>() 。这通常在使用T 的类的构造函数或main() 函数中完成。

注册类型后,可以使用QMetaType::fromName() 根据其名称找到它。

该函数在 Qt 6.5 中引入。

[noexcept] bool operator!=(const QMetaType &lhs, const QMetaType &rhs)

这是一个重载函数。

如果QMetaType lhs 代表的类型与QMetaType rhs 不同,则返回true ,否则返回false

[since 6.5] QDebug operator<<(QDebug d, QMetaType m)

QMetaType m 写入数据流d ,并返回数据流。

此函数在 Qt 6.5 中引入。

[noexcept] bool operator==(const QMetaType &lhs, const QMetaType &rhs)

这是一个重载函数。

如果QMetaType lhs 表示与QMetaType rhs 相同的类型,则返回true ,否则返回false

宏文档

Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE(Container)

该宏使Container 作为关联容器为QMetaType 所知。这使得将 Container<T, U> 的实例放入QVariant 成为可能,前提是 T 和 U 本身为QMetaType 所知。

需要注意的是,所有 Qt 关联容器都已内置支持,因此没有必要在这些容器中使用此宏。std::map 容器也有内置支持。

本例展示了 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 知道该类型。在QVariant 中将Type 作为自定义类型使用时需要使用该宏。

该宏要求Type 在使用时是完全定义的类型。对于指针类型,它还要求所指向的类型是完全定义的。与Q_DECLARE_OPAQUE_POINTER() 结合使用,可以注册指向前向声明类型的指针。

理想情况下,该宏应放在类或结构体声明的下方。如果做不到这一点,可以将其放在一个私有头文件中,每次在QVariant 中使用该类型时都必须包含该头文件。

添加 Q_DECLARE_METATYPE()后,所有基于模板的函数(包括QVariant )都会知道该类型。请注意,如果您打算在队列信号和槽连接或QObject 的属性系统中使用该类型,您还必须调用qRegisterMetaType(),因为名称是在运行时解析的。

本例展示了 Q_DECLARE_METATYPE() 的典型用例:

struct MyStruct
{
    int i;
    ...
};

Q_DECLARE_METATYPE(MyStruct)

如果MyStruct 位于命名空间中,则 Q_DECLARE_METATYPE() 宏必须位于命名空间之外:

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>();

有些类型是自动注册的,不需要使用这个宏:

注: 如果流运算符和调试运算符在注册时可见,本方法也会为该类型注册流运算符和调试运算符。由于在某些地方是自动完成的,因此强烈建议在类型本身之后直接声明类型的流运算符。由于 C++ 的查找规则与参数相关,因此强烈建议在与类型本身相同的命名空间中声明操作符。

流运算符应具有以下签名:

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

另请参见 qRegisterMetaType().

Q_DECLARE_OPAQUE_POINTER(PointerType)

使用该宏,可以通过Q_DECLARE_METATYPE() 或qRegisterMetaType() 将指向前向声明类型 (PointerType) 的指针注册到QMetaType

当被指向类型在程序的其他上下文中作为完整类型使用时,不要使用该宏以避免moc对不完整属性类型的投诉或错误。如果可以获得该类型的完整定义,但希望在头文件中使用前向声明以减少编译时间,请使用Q_MOC_INCLUDE

警告 不要在指向Q_OBJECT 或小工具类的指针中使用 Q_DECLARE_OPAQUE_POINTER,因为这样做有可能在元类型系统中引入不一致的信息。

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

Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE(Container)

这个宏使Container 作为顺序容器被QMetaType 知晓。这使得将 Container<T> 的实例放入QVariant 成为可能,前提是QMetaType 已知 T 本身。

请注意,所有 Qt 连续容器都已内置支持,因此无需在它们中使用此宏。std::vector 和 std::list 容器也有内置支持。

本例展示了 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)

该宏使得智能指针SmartPointerQMetaType 称为智能指针。这样,如果 T 是继承于QObject 的类型,就可以将 SmartPointer<T> 的实例放入QVariant

需要注意的是,QWeakPointerQSharedPointerQPointer 已经内置了支持,因此无需在它们中使用此宏。

本例展示了 Q_DECLARE_SMART_POINTER_METATYPE() 的典型用法:

#include <memory>Q_DECLARE_SMART_POINTER_METATYPE(std::shared_ptr)voidsomeFunc() {autosmart_ptr=std::make_shared<QFile>();    QVariantvar=QVariant::fromValue(smart_ptr);// ... 如果(var.canConvert< *>()QObject*>()) { QObject*sp =var.value<QObject*>();        qDebug() << sp->metaObject()->className(); // Prints 'QFile'.
    } }

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.