auto头文件 qt_QT中的元对象系统:创建自定义的QT类型

本文介绍了如何在QT中使用QVariant处理自定义类型,包括QVariant的类型枚举、转换函数以及如何注册自定义类型以使其支持QT的元对象系统。通过Q_DECLARE_METATYPE宏,可以使得自定义类能够存储在QVariant中,并在信号和槽的通信中使用。同时,文章提到了在多线程中使用信号和槽时,需要通过qRegisterMetaType注册类型以避免错误。
摘要由CSDN通过智能技术生成

原创文章,转载请注明出处,谢谢!

作者:清林,博客名:飞空静渡

QVariant可以表示QT中的大部分类型,它和pascal中的variant类型或c中的void类型有点相似,不过它的使用和c中的union类似,其实现也是用union,在qvariant.h头文件中,我们可以看到这样定义:

view plaincopy to clipboardprint?

class Q_CORE_EXPORT QVariant

{

public:

enum Type {

Invalid = 0,

Bool = 1,

Int = 2,

UInt = 3,

LongLong = 4,

ULongLong = 5,

......

UserType = 127,

#ifdef QT3_SUPPORT

IconSet = Icon,

CString = ByteArray,

PointArray = Polygon,

#endif

LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type

};

inline QVariant();

...............

}

class Q_CORE_EXPORT QVariant

{

public:

enum Type {

Invalid = 0,

Bool = 1,

Int = 2,

UInt = 3,

LongLong = 4,

ULongLong = 5,

......

UserType = 127,

#ifdef QT3_SUPPORT

IconSet = Icon,

CString = ByteArray,

PointArray = Polygon,

#endif

LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type

};

inline QVariant();

...............

}

我们可以用type()成员函数来返回它的类型:Type   QVariant::type () const 。

为了取得它的值,我们可以用类似的toT()这样的函数来取得,如toInt()、toString()等。

基本的使用如下:

view plaincopy to clipboardprint?

QDataStream out(...);

QVariant v(123);                // The variant now contains an int

int x = v.toInt();              // x = 123

out << v;                       // Writes a type tag and an int to out

v = QVariant("hello");          // The variant now contains a QByteArray

v = QVariant(tr("hello"));      // The variant now contains a QString

int y = v.toInt();              // y = 0 since v cannot be converted to an int

QString s = v.toString();       // s = tr("hello")  (see QObject::tr())

out << v;                       // Writes a type tag and a QString to out

...

QDataStream in(...);            // (opening the previously written stream)

in >> v;                        // Reads an Int variant

int z = v.toInt();              // z = 123

qDebug("Type is %s",            // prints "Type is int"

v.typeName());

v = v.toInt() + 100;            // The variant now hold the value 223

v = QVariant(QStringList());

QDataStream out(...);

QVariant v(123);                // The variant

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值