Qt中的强制类型转换

在C++开发中常常要进行数据类型的强制转换。html

刚开始学习的时候,直接对基本数据类型强制类型转换,如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: 用于进行没有任何关联之间的转换,好比一个字符指针转换为一个整形数。ide

QT框架提供的强制类型转换方法:函数

qobject_cast  qobject_cast()函数的行为相似于标准C ++ dynamic_cast(),其优势是不须要RTTI支持,而且它能够跨动态库边界工做。学习

QObject *obj = new QTimer;          // QTimer inherits QObjectui

QTimer *timer = qobject_cast<QTimer *>(obj);this

// timer == (QObject *)objspa

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

// 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().

 

等等...

相关文章
相关标签/搜索