B
B
BadCats2020-04-06 17:04:57
Qt
BadCats, 2020-04-06 17:04:57

Exception when adding QGraphicsItem to stage?

ball class:

#endif // BALL_H

ball.cpp:
#include "ball.h"

ball::ball(int x, int y,int R)
{
    this->x=x+10;
    this->y=y;
    this->R=R;
    ballObj = new QGraphicsEllipseItem(x,y,R,R);

}
void ball::setPos(int newX, int newY)
{
    this->x=newX;
    this->y=newY;
}
void ball::setSpeed(int newSpeed)
{
    this->speed=newSpeed;
}
QGraphicsEllipseItem* ball::getBall()
{
    return  this->ballObj;
}
QPoint ball::getPos()
{
    return QPoint(this->x,this->y);
}
int ball::getSpeed()
{
    return  this->speed;
}

Object creation:
ballObj=new ball(0,this->height(),10);

    gameBoard->scene()->addItem( ballObj->getBall());

The constructor - works fine - looked under the debugger: a
5e8b36b4b0901820264840.png
screenshot of the next step after the breakpoint is triggered
, but when I try to add it to the scene, I get a SegmentationFault - see the screenshot:
5e8b36ee6a442193137542.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2020-04-06
@vt4a2h

In C++, all pointers must be checked for null before use. You obviously have some kind of null pointer.
This code still looks suspicious:

allObj=new ball(0,this->height(),10);
gameBoard->scene()->addItem( ballObj->getBall());

The result of new is assigned to one variable, and then another is used. I assume this is a typo.
As I already wrote above, you need to check the result of the scene() call for null (most likely, this is where the error is), as well as the gameBoard itself.
And one more thing, you should understand that after calling the addItem(ballObj->getBall()) method, the returned object will go under the control of the scene (this is written in the documentation) and can be deleted at any time. That being said, who should remove ballObj in your code is not clear.
PS
This is no exception.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question