Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt forward declaration generates error

Tags:

c++

qt

qt4

When writting class TemplateHandler, say I use TemplateHandler.h (for my the header) and TemplateHandler.cpp (for the declarations). Like

// Templatehandler.h

#ifndef TEMPLATEHANDLER_H
#define TEMPLATEHANDLER_H

#include <QObject>   // Forward declaration of QObject generates error

class QListView;     // Forward declarations
class QTextEdit;
class QModelIndex;
class QStringListModel;

class TemplateHandler : public QObject
{
  Q_OBJECT
  public:
    TemplateHandler(QListView *view, QTextEdit *textEdit, QObject *parent);
    virtual ~TemplateHandler();

  private:
    QTextEdit *mTextEdit;
    QStringListModel *mModel;
};

#endif

And the source

#include "templatehandler.h"
#include <QListView>             // Inclusion of lib
#include <QTextEdit>
#include <QObject>
#include <QStringListModel>

TemplateHandler::TemplateHandler(QListView *view, QTextEdit *textEdit, QObject *parent) : QObject(parent), mTextEdit(textEdit)
{
    mModel = new QStringListModel(this);
    QStringList templates;
    templates << "<html>" << "</html>" << "<body>" << "</body>";
    mModel->setStringList(templates);
    view->setModel(mModel);
    connect(view, SIGNAL(clicked(const QModelIndex&)), SLOT(insertText(const QModelIndex&)));
}

TemplateHandler::~TemplateHandler() {
    // TODO Auto-generated destructor stub
}

But in this case forward declaration of QObject generates error, however the rest are okey. I need some help on that.

like image 469
Dewsworld Avatar asked Mar 09 '26 13:03

Dewsworld


1 Answers

This is a pure c++ "issue".

Forward declarations only work when the compiler do not need the size of the class at the time the header is included. E.g. for pointers, even to class, it knows the size.

On the other hand, for object created on the stack or for parent classes, it needs to know the exact size of the struct (e.g. sizeof(QObject)), which it can only get by including the .h.

like image 113
Chris Browet Avatar answered Mar 12 '26 02:03

Chris Browet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!