/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.