PDA

View Full Version : Add object to a scene from a sub class



Andre008
19th February 2016, 19:52
Hello,

i have create a dialog project with the Qt Creator which contains a code is as follows:


dialog.h:



class Dialog;
}

class Dialog : public QDialog
{
Q_OBJECT

public:
explicit Dialog(QWidget *parent = 0);
~Dialog();

private:
Ui::Dialog *ui;

QGraphicsScene *scene;

MemberClass mClass;
};


dialog.cpp


Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
}



From this point it is possible to add items with " scene->addItem(...)" to the scene.

How it is possible to add items to the scene from outside of the dialog class?

For Example:

memberClass.h


class MemberClass
{

public:
void addtoScene();
};



memberClass.cpp


void MemberClass::addtoScene()
{
//Here an item should be add to the scene of the dialog class
}



Thx,
Andre

anda_skoa
20th February 2016, 10:10
You can either make the scene accessible, or you add "additem" methods to your dialog class and call those.

Cheers,
_

Andre008
20th February 2016, 13:23
ok, i got one solution, but i think it is not an elegant one.
The static construct helps in this point.

dialog.h


class Dialog;
}

class Dialog : public QDialog
{
Q_OBJECT

public:
explicit Dialog(QWidget *parent = 0);
~Dialog();

private:
Ui::Dialog *ui;

static QGraphicsScene *scene;

MemberClass mClass;
};


dialog.cpp



QGraphicsScene* Dialog::scene = NULL;

Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
}


MemberClass.cpp


void MemberClass::addtoScene()
{
Dialog::scene->addItem(newItem);
}


The problem is to get the the specific object of the dialog class.

anda_skoa
20th February 2016, 13:42
The problem is to get the the specific object of the dialog class.
Just pass the pointer of the dialog class or the pointer of the scene to the mClass object, e.g. in its constructor.

Cheers,
_

Andre008
23rd February 2016, 00:31
Ok,t i got it,
Thx