Qt中的强制类型转换

在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<QTimer *>(obj);

// timer == (QObject *)obj

QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);

// button == 0

qgraphicsitem_cast  场景视图Item类转换

QGraphicsScene和 QGraphicsItem 的大多数便利函数(例如:items(),selectedItems()、collidingItems()、childItems())返回一个 QList<QGraphicsItem *> 列表,在遍历列表的时候,通常需要对其中的 QGraphicsItem 进行类型检测与转换,以确定实际的 item。

以下代码出处:https://blog.csdn.net/liang19890820/article/details/53612446

QList<QGraphicsItem *> items = scene->items();

foreach (QGraphicsItem *item, items) {

    if (item->type() == QGraphicsRectItem::Type) {        // 矩形

        QGraphicsRectItem *rect = qgraphicsitem_cast<QGraphicsRectItem*>(item);

        // 访问 QGraphicsRectItem 的成员

    } else if (item->type() == QGraphicsLineItem::Type) {      // 直线

        QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem*>(item);

        // 访问 QGraphicsLineItem 的成员

    } else if (item->type() == QGraphicsProxyWidget::Type) {    // 代理 Widget

        QGraphicsProxyWidget *proxyWidget = qgraphicsitem_cast<QGraphicsProxyWidget*>(item);

        QLabel *label = qobject_cast<QLabel *>(proxyWidget->widget());

        // 访问 QLabel 的成员

    } else if (item->type() == CustomItem::Type) {         // 自定义 Item

        CustomItem *customItem = qgraphicsitem_cast<CustomItem*>(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().

 

等等...

原文地址:https://www.cnblogs.com/MakeView660/p/11045437.html