QGraphicsItem Custom class-> type() 不起作用

QGraphicsItem custom class-> type() not working

本文关键字:type 不起作用 gt Custom class- QGraphicsItem      更新时间:2023-10-16

我在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 thanks in advance

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

实际上并没有重写类型函数。您的int type()函数是非const的,而类文档显示虚拟QGraphicsItem函数是const的。constness需要匹配你的函数来覆盖QGraphicsItem函数。

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

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

当您使用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