Qt C++ inner class access to outer class

663 Views Asked by At

I have a question again: I have a class PBV t(inherits from Tab) hat has a class Geometry. Geometry is the parent of Geo_1. From Geo_1 I want to have access to methods of PBV ( e.g. printContent . How do I do that? I am able to create Signal-Slots but since I have to use methods of PBV often that would make lots of Signal-Slots. 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() { }
1

There are 1 best solutions below

0
On

One approach, as referred to by comments, is to keep track of the parent class in the constructor of the child:

In Geometry.h, add a private member variable:

private: 
  PBV* m_pParentPBV;

Then, in the constructor in Geometry.cpp, set this to the parent you are already passing:

Geometry::Geometry(QObject *_parent)
     : QObject(_parent)     
{
    m_pParentPBV = dynamic_cast<PBV*>(_parent);
}

Now you can call methods on the parent using m_pParentPBV->printContent() etc.