0

我又有一个问题:我有一个类 PBV t(从 Tab 继承)帽子有一个类 Geometry。Geometry 是 Geo_1 的父级。从 Geo_1 我想访问 PBV 的方法(例如 printContent 。我该怎么做?我可以创建信号槽,但由于我必须经常使用 PBV 的方法,这会产生很多信号槽。这里是我的代码:

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() { }
4

1 回答 1

0

注释中提到的一种方法是在子类的构造函数中跟踪父类:

在 Geometry.h 中,添加一个私有成员变量:

private: 
  PBV* m_pParentPBV;

然后,在 Geometry.cpp 的构造函数中,将其设置为您已经传递的父级:

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

m_pParentPBV->printContent()现在您可以使用etc调用父级上的方法。

于 2017-01-16T18:14:29.037 回答