user3443063
user3443063

Reputation: 1615

Qt C++ use method of creating class in created objects

I`m still stuck.

I have a GUI-class that creates an Object. From a method of this new Object I want to use methods of the creating class

I have a Gui(PBV) with line_Edits and a Combobox. In this Combobox I can choose between different Geometries. Geo_1, Geo_2,… that inherit from Geometry. According to the entries in the combobox I want to create different Objects (Geo_1,Geo_2,…) that then set the lineEdits of the creating class according to the needs of the Geo_n-Object.

I don`want to do that with signal-slot

I asked different questions on that but I can`t get further.

I somehow feel this is kind of recursive... Is there a solution fort hat?

Here is my code:

PBV.h:

#include "../Geometry/Geo_1.h"

 class PBV : public Tab
 {
     Q_OBJECT    
 public:
     explicit PBV (QWidget *parent = 0);
     ~ PBV ();
     virtual void printContent( QStringList *const qsl);

private:    
    Geo_1 *GEO_1;
    Geometry *GEO;
 }

PBV.cpp:

 …
 Geo_1 *GEO_1;
 GEO_1 = new Geo_1(this);
 GEO_1->set_LNE_default();
 …

.

Geo_1.h:
#ifndef GEO_1_H
#define GEO_1_H 
#include "Geometry.h"
#include "../Tabs/PBV.h"
class Geo_1: public Geometry
{
   Q_OBJECT
public:
    Geo_1 (QObject *_parent = 0);
    virtual void set_LNE_default();
};  
#endif // GEO_1_H

.

Geo_1.cpp:
#include "Geometry.h"
#include <QDebug>
#include "Geo_1.h"
#include "../Tabs/PBV.h"

Geo_1::Geo_1(QObject*_parent)
: Geometry(_parent) {}

void Geo_1::set_LNE_default()
{
    // here I want to use printContent  
}

.

Geometry.h:

 #ifndef GEOMETRY_H
 #define GEOMETRY_H
 #include <QObject>

 class Geometry : public QObject
 {
     Q_OBJECT
 public:
     Geometry(QObject *_parent=0);
     ~Geometry();
     virtual void set_LNE_default();
 };
 #endif // GEOMETRY_H

.

Geometry.cpp:

 #include "Geometry.h"
 #include <QDebug>

 Geometry::Geometry(QObject *_parent)
     : QObject(_parent)     {}

 Geometry::~Geometry(){}
 void Geometry::set_LNE_default() { }

Upvotes: 0

Views: 496

Answers (1)

Steeve
Steeve

Reputation: 1341

When PBV allocates a Geo_1 instance, it is already passing a pointer to itself in the constructor:

GEO_1 = new Geo_1(this); // "this" is your PBV instance

Why not save the pointer to use later?

Geo_1::Geo_1(PBV*_parent) : Geometry((QObject*)_parent)
{
    this->pbv = _parent; // Save reference to parent
}

Then you can do:

void Geo_1::set_LNE_default()
{
    // here I want to use printContent
    this->pbv->printContent(...); // this->pbv is your saved ptr to the PBV that created this instance
}

EDIT

Additonally, you might run into the problem that you will have to cross-include the two headers (PBV and Geo_1), to fix this, remove the include for Geo_1 from PBV.h and forward-declare Geo_1. Just like this:

class Geo_1;

Before declaring your PBV class.

Upvotes: 3

Related Questions