【问题标题】:Qt - invalid conversion to child classQt - 无效转换为子类
【发布时间】:2010-04-24 01:22:27
【问题描述】:

我正在使用图形视图框架绘制多边形。我用这个在场景中添加了一个多边形:

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));

我做错了什么?

【问题讨论】:

    标签: qt inheritance qgraphicsview qgraphicsitem


    【解决方案1】:

    一般来说,由于“切片”,派生类的指针指向父类并不是一个好主意。我建议你改为这样做

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

    【讨论】:

    • 在你展示的情况下,我的 GridHex 对象不会被切片,因为 QGraphicsScene::addItem() 接收 QGraphicsItem 作为参数?
    【解决方案2】:

    我猜 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);
    

    【讨论】:

    • 哦,对了,我想我在这里做错了。我还是有点熟悉这个框架。之前没有想过要继承 QGraphicsScene,但这就是我必须要做的。
    • 所以如果我想在场景中添加自定义项目,我必须继承 QGraphicsScene 才能接受我的自定义项目?我应该如何设置 QGraphicsScene 子类才能将我的自定义项目添加到它?
    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多