Pregunta

I have two custom types placed on a QGraphicsScene, this is their declaration:

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: 
};

and

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: 
};

Now, when I select an item on the QGraphicsScene, I want to find out which type of those two classes it is, but how do I do this? I tried the following, but it always returns the same type... :S thanks in advance

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

Solución

You aren't actually overriding the type function. Your int type() function is non-const, while the class documentation shows that the virtual QGraphicsItem function is const. The constness needs to match for your function to override of the QGraphicsItem function.

If you have a C++11 compiler, you can specify override to ensure it is a compiler error if your function does not actually override a virtual method. As of Qt5, there is a macro Q_DECL_OVERRIDE defined in QtGlobal which will become the override keyword for compilers that support it, or nothing for compilers that do not.

I also notice you're also checking item->type()==7 and item->type()==8. In the version of Qt I have handy (4.7.2), those type values correspond to QGraphicsPixmapItem and QGraphicsTextItem, respectively. Are you sure those are the values you're looking for? I'd expect the comparisons to be item->type() == FotoGebouw::TypeFotoGebouw and item->type() == FotoGebouw::TypeFotoPlantage.

Otros consejos

There will be problem when you use qgraphicsitem_cast with your method,

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

You should follow the example in the document http://qt-project.org/doc/qt-4.8/qgraphicsitem.html#type

Declare your Type and return it as result in int type() const

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top