我在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();
答案 0 :(得分:3)
您实际上并没有覆盖类型函数。您的int type()
函数是非const,而the class documentation表示虚拟QGraphicsItem函数是const。 constness需要匹配你的函数来覆盖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
。
答案 1 :(得分:0)
使用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