2010-04-23 48 views
0

我正在使用Graphics View框架繪製多邊形。我添加了一個多邊形場景以這樣的:Qt - 無效轉換爲子類

QGraphicsPolygonItem *poly = scene->addPolygon(QPolygonF(vector_of_QPointF)); 
poly->setPos(some_point); 

但我需要實現類似的選擇,鼠標指針,並在圖形項其他類似的東西,一些自定義的行爲。因此,我宣佈一個類繼承QGraphicsPolygonItem:

#include <QGraphicsPolygonItem> 

class GridHex : public QGraphicsPolygonItem 
{ 
public: 
    GridHex(QGraphicsItem* parent = 0); 
}; 

GridHex::GridHex(QGraphicsItem* parent) : QGraphicsPolygonItem(parent) 
{ 
} 

沒有做多少與該類到目前爲止,你可以看到。但是不應該用我的GridHex類工作替換QGraphicsPolygonItem?這是拋出一個「從‘QGraphicsPolygonItem *’的無效轉換到‘GridHex *’」錯誤:

GridHex* poly = scene->addPolygon(QPolygonF(vector_of_QPointF)); 

我在做什麼錯?

回答

0

我猜scene-> addPolygon返回一個QGraphicsPolygonItem,這是一個基類的專業化。您需要進行動態投射,因爲您只能通過上升梯度而不是下降來安全地進行轉換。

GridHex* poly = dynamic_cast<GridHex*>(scene->addPolygon(QPolygonF(vector_of_QPointF))); 
if (poly != NULL) { 
    // You have a gridhex! 
} 

編輯:雖然我的回答您的問題轉換幫助,你怎麼能保證場景創建GridHex對象嗎?你是否打算繼承場景對象以返回你的GridHex對象?

你的QGraphicsScene子類會覆蓋addPolygon做這樣的事情:

// Call the base class 
QGraphicsPolygonItem* result = QGraphicsScene::addPolygon(vectorOfPoints); 
// Return your stuff 
return new GridHex(result); 
+0

哦,對,我想我在這裏做的一切都是錯的。我仍然有點熟悉框架。以前沒有想過子類化QGraphicsScene,但那就是我必須做的。 – 2010-04-23 13:38:09

+0

所以,如果我想添加自定義項目的場景,我得到子類QGraphicsScene能夠接受我的自定義項目?我應該如何設置一個QGraphicsScene子類來添加我的自定義項目呢? – 2010-04-23 13:56:37

1

通常,由於「切片」,派生類的指針指向父項不是一個好主意。我建議你這樣做,而不是

GridHex* hex = new GridHex(scene); 
scene->addItem(hex); 
+0

感謝切片提示。 – 2010-04-23 13:49:45

+0

在你顯示的情況下,我的GridHex對象是否會被切片,因爲QGraphicsScene :: addItem()接收到一個QGraphicsItem作爲參數? – 2010-04-23 18:16:47