QVariant使用

The QVariant class acts like a union for the most common Qt data types.
QVariant 类作用类似与绝大部分Qt数据类型。

        Because C++ forbids unions from including types that have non-default constructors or destructors, most interesting Qt classes cannot be used in unions. Without QVariant, this would be a problem for QObject::property() and for database work, etc.
A QVariant object holds a single value of a single type() at a time. (Some type()s are multi-valued, for example a string list.) You can find out what type, T, the variant holds, convert it to a different type using convert(), get its value using one of the toT() functions (e.g., toSize()) and check whether the type can be converted to a particular type using canConvert().

        因为C++禁止联合体包含非默认构造函数或析构函数的类型,所以大多数有趣的QT类不能用于联合。如果没有QVariant,这对QObject::property()和数据库工作来说都是一个问题

        QVariant对象一次只保存一个类型()的单个值。(有些类型()是多值的,例如字符串列表。)您可以找出变量所包含的类型T,使用convert()将其转换为其他类型,使用toT()函数之一(例如toSize())获取其值,并使用canConvert()检查是否可以将该类型转换为特定类型。


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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值