在qt私有类上使用不完整类型无效

时间:2013-08-01 13:02:24

标签: qt pimpl-idiom

我想在Q_D宏的帮助下在派生类中使用d指针。

这是我的父类:

class DIGIKAM_EXPORT GraphicsDImgView : public QGraphicsView
{
    Q_OBJECT

public:
    class GraphicsDImgViewPrivate;

protected:
    GraphicsDImgViewPrivate* const d_ptr;

protected:
    Q_DECLARE_PRIVATE(GraphicsDImgView)
};

和我的GraphicsDImgViewPrivate类:

class GraphicsDImgView::GraphicsDImgViewPrivate
{
public:

    GraphicsDImgViewPrivate()
    {
        scene            = 0;
        item             = 0;
        layout           = 0;
        cornerButton     = 0;
        panIconPopup     = 0;
        movingInProgress = false;
        showText         = true;
    }

    QGraphicsScene*           scene;
    GraphicsDImgItem*         item;
    SinglePhotoPreviewLayout* layout;

    QToolButton*              cornerButton;
    KPopupFrame*              panIconPopup;

    QPoint                    mousePressPos;
    QPoint                    panningScrollPos;
    bool                      movingInProgress;
    bool                      showText;
};

GraphicsDImgView::GraphicsDImgView(QWidget* const parent)
    : QGraphicsView(parent), d_ptr(new GraphicsDImgViewPrivate)
{
    Q_D(GraphicsDImgView);
    d->scene  = new QGraphicsScene(this);
    d->scene->setItemIndexMethod(QGraphicsScene::NoIndex);

    setScene(d->scene);
    d->layout = new SinglePhotoPreviewLayout(this);
    d->layout->setGraphicsView(this);
}

派生的类中,我编写了一个方法,我想在其中使用GraphicsDImgView的d指针:

bool ImageRegionWidget::movingInProgress()
{
    Q_D(GraphicsDImgView);
    return d->movingInProgress;
}

但是构建会给我以下错误消息

  

在成员函数'bool Digikam :: ImageRegionWidget :: movingInProgress()':... path ....   错误:无效使用不完整类型'类GraphicsDImgView :: GraphicsDImgViewPrivate'

  

graphicsdimgview.h:128:11:错误:'类GraphicsDImgView :: GraphicsDImgViewPrivate'的前向声明

我完全按照文档进行操作,所以我不知道哪里出错了。也许我在粗心大意。请帮我指出我的错误。谢谢:))

1 个答案:

答案 0 :(得分:3)

我无法纠正您的样本中的错误。代码很安静,不清楚。我不知道文章,你得到这样的推荐。我的建议是以下一种方式做pimpl:

MyClass.h

class MyClassPrivate;
class MyClass
    : public QObject
{
Q_OBJECT
public:
  explicit MyClass(QObject *parent = 0);
~MyClass()
protected:
  MyClassPrivate * const d_ptr;
  MyClass(MyClassPrivate &dd, QObject * parent);
private:
  Q_DECLARE_PRIVATE(MyClass);
};

MyClass_p.h

#include "myclass.h"

class MyClassPrivate
{
  Q_DECLARE_PUBLIC(MyClass);
public:
  MyClassPrivate();
  virtual ~MyClassPrivate();

  MyClass * q_ptr;
};

MyClass.cpp

#include "myclass.h"
#include "myclass_p.h"

MyClassPrivate::MyClassPrivate()
{}

MyClassPrivate::~MyClassPrivate()
{}

MyClass::MyClass(QObject *parent)
  :QObject(parent)
  ,d_ptr(new MyClassPrivate())
{
  Q_D(MyClass);
  d->q_ptr = this;
}

MyClass::MyClass(MyClassPrivate &dd, QObject * parent)
  :QObject(parent)
  ,d_ptr(&dd)
{
  Q_D(MyClass);
  d->q_ptr = this;
}

MyClass::~MyClass()
{
  Q_D(MyClass);
  delete d;
}