Qt 中的强制类型转换:qvariant |
您所在的位置:网站首页 › qvariant转化为字符串 › Qt 中的强制类型转换:qvariant |
在 C++ 开发中经常要进行数据类型的强制转换。 开始的直接对基本数据类型强制类型转换,如 float fnum = 3.14; int num = (int) fnum; 随着 C++ 标准的发展,又提供了 dynamic_cast、const_cast 、static_cast、reinterpret_cast 等高级安全的强制转换方法。 dynamic_cast: 通常在基类和派生类之间转换时使用,run-time cast。 const_cast: 主要针对 const 和 volatile 的转换。 static_cast: 一般的转换,no run-time check. 通常,如果你不知道该用哪个,就用这个。 reinterpret_cast: 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整形数。 QT 框架提供的强制类型转换方法: qobject_cast qobject_cast () 函数的行为类似于标准 C ++ dynamic_cast (),其优点是不需要 RTTI 支持,并且它可以跨动态库边界工作。 QObject *obj = new QTimer; // QTimer inherits QObject QTimer *timer = qobject_cast(obj); // timer == (QObject *)obj QAbstractButton *button = qobject_cast(obj); // button == 0 qgraphicsitem_cast 场景视图 Item 类转换QGraphicsScene 和 QGraphicsItem 的大多数便利函数(例如:items (),selectedItems ()、collidingItems ()、childItems ())返回一个 QList 列表,在遍历列表的时候,通常需要对其中的 QGraphicsItem 进行类型检测与转换,以确定实际的 item。 QList items = scene->items(); foreach (QGraphicsItem *item, items) { if (item->type() == QGraphicsRectItem::Type) { // 矩形 QGraphicsRectItem *rect = qgraphicsitem_cast(item); // 访问 QGraphicsRectItem 的成员 } else if (item->type() == QGraphicsLineItem::Type) { // 直线 QGraphicsLineItem *line = qgraphicsitem_cast(item); // 访问 QGraphicsLineItem 的成员 } else if (item->type() == QGraphicsProxyWidget::Type) { // 代理 Widget QGraphicsProxyWidget *proxyWidget = qgraphicsitem_cast(item); QLabel *label = qobject_cast(proxyWidget->widget()); // 访问 QLabel 的成员 } else if (item->type() == CustomItem::Type) { // 自定义 Item CustomItem *customItem = qgraphicsitem_cast(item); // 访问 CustomItem 的成员 } else { // 其他类型 item } }需要注意的是,为了使该函数正确使用自定义 Item,需要在 QGraphicsItem 子类中重写 type () 函数才行。 class CustomItem : public QGraphicsItem { public: enum { Type = UserType + 1 }; int type() const override { // Enable the use of qgraphicsitem_cast with this item. return Type; } ... }; qvariant_cast QVariant 类型转换为实际的类型Returns the given value converted to the template type T. This function is equivalent to QVariant::value(). |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |