Search code examples
c++qtincludeforward-declaration

C++ Qt4.8 :: Pass Object to another Class - member access into incomplete type error


I am new in C++ Qt and struggling with the correct use of forward declarations and #include.

What I want to do:

  • I have a Qt Gui (Class Ui::Gui) where we can set values.
  • I want to save these values in Gui Class variables.
  • As soon as a button (Generate Xml) is clicked, I want to pass the object 'ui' to the XmlGeneratorClass, So i can use the values to generate a Xml.

gui.h

#ifndef GUI_H
#define GUI_H

#include <QMainWindow>
#include <QDebug>
#include "xmlgeneratorqobject.h"

namespace Ui {
class Gui;
}

class Gui : public QMainWindow
{
Q_OBJECT

public:
explicit Gui(QWidget *parent = nullptr);
~Gui();

qint8 testvalue = 1;

signals:
   void transmitToXmlGen(Ui::Gui*);

private slots:
   void on_pushButtonGenerateXml_clicked();

private:
    Ui::Gui *ui;
    XmlGeneratorQObject *xmlgenerator = new XmlGeneratorQObject();
};

#endif // GUI_H

gui.cpp

#include "gui.h"
#include "ui_gui.h"

Gui::Gui(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Gui)
{
    ui->setupUi(this);
  connect(this,SIGNAL(transmitToXmlGen(Ui::Gui*)),xmlgenerator,SLOT(receiveFromGui(Ui::Gui*)));

}

Gui::~Gui()
{
    delete ui;
}

void Gui::on_pushButtonGenerateXml_clicked()
{
    emit transmitToXmlGen(ui);
}

xmlgeneratorqobject.h

#ifndef XMLGENERATORQOBJECT_H
#define XMLGENERATORQOBJECT_H

#include <QObject>
#include <QDebug>

namespace Ui {
class XmlGeneratorQObject;
class Gui;
}

class XmlGeneratorQObject : public QObject {
Q_OBJECT

public:
    explicit XmlGeneratorQObject(QObject * parent = nullptr);

private slots:

    void receiveFromGui(Ui::Gui*);
};

#endif // XMLGENERATORQOBJECT_H

xmlgeneratorqobject.cpp

#include "xmlgeneratorqobject.h"

XmlGeneratorQObject::XmlGeneratorQObject(QObject *parent){}


void XmlGeneratorQObject::receiveFromGui(Ui::Gui* objectFromGui)
{
      qDebug() << objectFromGui->testvalue; // ERROR member access into     incomplete type 'Ui::Gui'
}

Expected result: Access to public variables from passed gui-object should be possible

Actual result: member access into incomplete type 'Ui::Gui'

Can you please help me learn forward declaration / include? Is my approach in general okay?


Solution

  • Your xmlgeneratorqobject.cpp needs the line

    #include "ui_gui.h"
    

    This gives it the details of the ui widgets. This file is generated by the Qt build system.