Casting of a QGraphicsItem subclass
Hello,
i'm new in QT and i'm having problems with QGraphicsItem and my suclassed "Item".
I have a QGraphicsView that contains a QGraphicsScene in which i'm inserting some items.
Those items are a subclass of QGraphicsItem and i have called it TestHoverItem (It contains some additional values).
If i try to get one of the object i have in the QGraphicsScene using the itemAt() function i have no problem (code below)
Code:
QPoint point
= e
->scenePos
().
toPoint();
auto sceneTop = scene();
QGraphicsItem *item
= sceneTop
->itemAt
(point.
x(), point.
y(),QTransform
());
TestHoverItem *hover = qgraphicsitem_cast<TestHoverItem *>(item);
qDebug
() <<
"Codice " <<
QString::number(hover
->getCodice
());
If i try to get all the objects from the QGraphicsScene using the items() function the application crashes
Code:
QList<QGraphicsItem *> items;
items = sceneTop->items();
qDebug
() <<
"Numero items " + QString::number(items.
size());
//Fin qui tutto bene
TestHoverItem * aa= new TestHoverItem();
for(int i=0; i<items.size(); i++){
aa =qgraphicsitem_cast<TestHoverItem *>(items[i]);
qDebug
() <<
"Codice: " +QString::number(aa
->getCodice
());
}
Can someone explain me what i'm doing wrong?
Thank you for the time and , i hope , for the answers
Re: Casting of a QGraphicsItem subclass
Quote:
TestHoverItem * aa= new TestHoverItem();
Why do you do this? You need a variable to hold a pointer to a TestHoverItem, not a new item.
Quote:
aa =qgraphicsitem_cast<TestHoverItem *>(items[i]);
If the item is -not- a TestHoverItem, then the cast returns a NULL pointer. You then proceed to use that pointer (without checking to see if it -is- NULL) in the qDebug() statement that follows.