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

 

等等...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM