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