结果:
b.ljtcnt() 8889
b.ljtcnt() 1457
代码如下:
DrawToolButton.h:
#ifndef DrawToolButton_H
#define DrawToolButton_H
#include <QToolButton>
class DrawToolButtonPrivate;
class DrawToolButton
{
public:
DrawToolButton(QWidget *parent=0);
~DrawToolButton();//析构函数必须把定义放到CPP中 否则编译通不过
Q_PROPERTY(int txcnt READ txcnt WRITE settxcnt)
int txcnt() const;
void settxcnt(int i);
private:
QScopedPointer<DrawToolButtonPrivate> d_ptr;
Q_DISABLE_COPY(DrawToolButton)
Q_DECLARE_PRIVATE(DrawToolButton)
};
#endif
DrawToolButton.cpp:
#include "DrawToolButton.h"
#include <qobject.h>
class DrawToolButtonPrivate
{
Q_DECLARE_PUBLIC(DrawToolButton)
inline DrawToolButtonPrivate()
: q_ptr(0)
{}
public:
int prljltcnt;
void init();
private:
DrawToolButton *q_ptr;
};
void DrawToolButtonPrivate::init()
{
Q_Q(DrawToolButton);
prljltcnt = 8889;
}
DrawToolButton::DrawToolButton(QWidget * parent)
: d_ptr(new DrawToolButtonPrivate)
{
d_ptr->q_ptr = this;
Q_D(DrawToolButton);
d->init();
}
DrawToolButton::~DrawToolButton()
{
<pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" color:#808bed;">delete</span><span style=" color:#646482;"> </span><span style=" font-weight:600;">d_ptr</span><span style=" color:#cfbfad;">;</span>
d_ptr = NULL;
}int DrawToolButton::txcnt() const{ Q_D(const DrawToolButton); return d->prljltcnt;}void DrawToolButton::settxcnt(int i){ Q_D(DrawToolButton); if (d->prljltcnt == i) return; d->prljltcnt = i;}调用:DrawToolButton b; qDebug()<<"b.ljtcnt()"<<b.txcnt(); b.settxcnt(1457); qDebug()<<"b.ljtcnt()"<<b.txcnt();
另外一种方案:
DrawToolButton.h:
#ifndef DrawToolButton_H
#define DrawToolButton_H
#include <QToolButton>
class DrawToolButtonPrivate;
class DrawToolButton : public QToolButton
{
Q_OBJECT
public:
DrawToolButton(QWidget *parent=0);
~DrawToolButton();//析构函数必须把定义放到CPP中 否则编译通不过
Q_PROPERTY(int txcnt READ txcnt WRITE settxcnt)
int txcnt() const;
void settxcnt(int i);
private:
QScopedPointer<DrawToolButtonPrivate> d_ptr;
Q_DISABLE_COPY(DrawToolButton)
Q_DECLARE_PRIVATE(DrawToolButton)
};
#endif
DrawToolButton.cpp:
#include "DrawToolButton.h"
#include <qobject.h>
class DrawToolButtonPrivate
{
Q_DECLARE_PUBLIC(DrawToolButton)
inline DrawToolButtonPrivate()
: q_ptr(0)
{}
public:
int prljltcnt;
void init();
void aboutToDestroy() {}
private:
DrawToolButton *q_ptr;
};
void DrawToolButtonPrivate::init()
{
Q_Q(DrawToolButton);
prljltcnt = 8889;
}
DrawToolButton::DrawToolButton(QWidget * parent)
: d_ptr(new DrawToolButtonPrivate)
{
d_ptr->q_ptr = this;
Q_D(DrawToolButton);
d->init();
}
DrawToolButton::~DrawToolButton()
{
}
int DrawToolButton::txcnt() const
{
Q_D(const DrawToolButton);
return d->prljltcnt;
}
void DrawToolButton::settxcnt(int i)
{
Q_D(DrawToolButton);
if (d->prljltcnt == i)
return;
d->prljltcnt = i;
}