【问题标题】:QGraphicsItem custom class-> type() not workingQGraphicsItem 自定义类-> type() 不工作
【发布时间】:2014-04-17 17:19:15
【问题描述】:

我在 QGraphicsScene 上放置了两个自定义类型,这是它们的声明:

class FotoGebouw : public QGraphicsItem
{
public:
    explicit FotoGebouw();
    ~FotoGebouw();
    Gebouw *linkGebouw;
    enum ItemType { TypeFotoGebouw = UserType + 1, TypeFotoPlantage = UserType + 2};
    int type(){ return TypeFotoGebouw; }
signals:  
public slots: 
};

和

class FotoPlantage : public QGraphicsItem
{
public:
    explicit FotoPlantage();
    ~FotoPlantage();
    Plantage *linkPlantage;
    enum ItemType { TypeFotoGebouw = UserType + 1, TypeFotoPlantage = UserType + 2};
    int type(){ return TypeFotoPlantage; }   
signals:  
public slots: 
};

现在,当我在 QGraphicsScene 上选择一个项目时,我想知道它是这两个类的哪一种类型,但我该怎么做呢?我尝试了以下方法,但它总是返回相同的类型......:S提前感谢

    QGraphicsItem *item = bordscene->selectedItems().at(0);
        if (item->type()==7)
            checkGebouwSelectie();
        else if (item->type()==8)
            checkPlantageSelectie();

【问题讨论】:

    标签: c++ qt class qgraphicsitem


    【解决方案1】:

    您实际上并没有覆盖 type 函数。您的 int type() 函数是非常量的,而 the class documentation 显示虚拟 QGraphicsItem 函数是 const。常量需要匹配您的函数以覆盖 QGraphicsItem 函数。

    如果您有 C++11 编译器,您可以指定 override 以确保如果您的函数实际上没有覆盖虚拟方法,这是编译器错误。从 Qt5 开始,QtGlobal 中定义了一个宏 Q_DECL_OVERRIDE,它将成为支持它的编译器的 override 关键字,或者不支持它的编译器。

    我还注意到您也在检查item->type()==7 和item->type()==8。在我方便的 Qt 版本(4.7.2)中,这些类型值分别对应于 QGraphicsPixmapItem 和 QGraphicsTextItem。你确定这些是你正在寻找的价值观吗?我希望比较是item->type() == FotoGebouw::TypeFotoGebouw 和item->type() == FotoGebouw::TypeFotoPlantage。

    【讨论】:

    • 这些方法似乎都不起作用:S 尝试将其设为 const,尝试使用覆盖并尝试使用不同的编译器:S
    • @CédricVandelaer 太好了!我已将我的评论添加到答案中。既然解决了你的问题,你能接受吗?
    【解决方案2】:

    在你的方法中使用qgraphicsitem_cast会有问题,

    template <class T> inline T qgraphicsitem_cast(QGraphicsItem *item)
    {
        return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
            || (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
    }
    

    您应该按照文档http://qt-project.org/doc/qt-4.8/qgraphicsitem.html#type中的示例进行操作

    声明您的Type 并将其作为结果返回int type() const

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2014-06-25
      • 2020-08-31
      相关资源
      最近更新 更多