質問

I have my abstract class (A), which describes a field trip and Qt base class QGraphicsItem, which describes the Qt functions for controlling items . I want to inherit from these classes to their items .

The problem is that the list of items stored in a QList <QGraphicsItem *>, making it impossible to access the fields A :: directly, and do not want to use dynamic_cast . What are the other options?

It is important that the item may not be the final child, ie it can be inherited from other items (as well through multiple inheritance ) .

In QList <QGraphicsItem *> be kept only the elements inherited from A and QGraphicsItem. What are your suggestions ? Thank you for your help.

UPD1: this code:

    QList<QGraphicsItem *> items=scene->items();
    for(int i=0;i<items.size();++i){
        std::cerr<<"\n"<<items.at(i)->entity::getX();
    }

(entity is A) throw an error:

/home/user/works/cpp/QT/Objcts/src/mainwindow.cpp:87: error: 'entity' is not a base of 'QGraphicsItem' std::cerr<<"\n"<<items.at(i)->entity::getX(); ^

役に立ちましたか?

解決

/home/user/works/cpp/QT/Objcts/src/mainwindow.cpp:87: error: 'entity' is not a base of 'QGraphicsItem' std::cerr<<"\n"<entity::getX();

You are trying to access a base class, whereas your entity class (weirdly named without CamelCase) is not inheriting that.

Right, so this is the use case for which dynamic casts, like dynamic_cast in C++ was invented. You should utilize it.

That being said, for QObjects, it is even better to use the qobject_cast in the Qt world rather than the raw dynamic_cast. QGraphicsItem is intentionally not QObject, although your other base (entity) might be, but that is not relevant.

This code should get you going:

QList<QGraphicsItem *> items = scene->items();
foreach (GraphicsItem* item, items) {
    entity *e = dynamic_cast<entity*>(item);
    if (e)
        qDebug() << e->getX();
}

Disclaimer: I have not tested this code, but the concept is valid, I think.

There is no need for neither stderr, nor explicit indexing loop. You could use the Qt debug functionality to print as you wish, and foreach to go through the elements.

Also, in the Qt world, "getX" is not really a common convention. People tend to prefer to drop the "get" prefix in favor of less typing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top